symref
Version:
Static code checker for AI code agents (Windsurf, Cline, etc.)
81 lines • 3.4 kB
JavaScript
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import { useState, useEffect } from 'react';
// カウンターのカスタムフック
const useCounter = (initialValue = 0, step = 1) => {
const [count, setCount] = useState(initialValue);
const increment = () => {
setCount(prevCount => prevCount + step);
};
const decrement = () => {
setCount(prevCount => prevCount - step);
};
const reset = () => {
setCount(initialValue);
};
return { count, increment, decrement, reset };
};
// 永続化データのカスタムフック
const useLocalStorage = (key, initialValue) => {
// 初期値を読み込む
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
}
catch (error) {
console.error(error);
return initialValue;
}
});
// 値をローカルストレージに保存する
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
};
// ウィンドウサイズを監視するカスタムフック
const useWindowSize = () => {
const [windowSize, setWindowSize] = useState({
width: typeof window !== 'undefined' ? window.innerWidth : 0,
height: typeof window !== 'undefined' ? window.innerHeight : 0,
});
useEffect(() => {
// ハンドラ関数
const handleResize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
// イベントリスナーを追加
window.addEventListener('resize', handleResize);
// クリーンアップ関数
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return windowSize;
};
// カスタムフックを使用するコンポーネント
const CounterComponent = () => {
const { count, increment, decrement, reset } = useCounter(0, 2);
return (_jsxs("div", { children: [_jsxs("p", { children: ["Count: ", count] }), _jsx("button", { onClick: increment, children: "Increment" }), _jsx("button", { onClick: decrement, children: "Decrement" }), _jsx("button", { onClick: reset, children: "Reset" })] }));
};
// 複数のカスタムフックを組み合わせるコンポーネント
const PersistentCounterComponent = () => {
const [persistentCount, setPersistentCount] = useLocalStorage('counter', 0);
const windowSize = useWindowSize();
const increment = () => {
setPersistentCount(prevCount => prevCount + 1);
};
return (_jsxs("div", { children: [_jsxs("p", { children: ["Persistent Count: ", persistentCount] }), _jsxs("p", { children: ["Window Size: ", windowSize.width, " x ", windowSize.height] }), _jsx("button", { onClick: increment, children: "Increment" })] }));
};
export { useCounter, useLocalStorage, useWindowSize, CounterComponent, PersistentCounterComponent };
//# sourceMappingURL=CustomHooks.test.js.map