Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Custom Hooks are user-defined functions that use built-in React hooks (useState, useEffect, useMemo, etc.) to encapsulate and reuse logic across different components.
Main rule: custom hook name must start with use so React understands it's a hook and applies corresponding rules.
You can extract related business logic (e.g., API work, forms, timers) into separate hook and use it in multiple places.
Instead of repeating same useEffect or useState in multiple components, you write hook once and reuse it.
Components become smaller and cleaner if main logic is extracted into hooks.
function Component() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return <p>Width: {width}px</p>;
}
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
// Usage
function Component() {
const width = useWindowWidth();
return <p>Width: {width}px</p>;
}
useFetch, useUserData)useForm, useInput)useModal)useLocalStorage)useInterval, useDebounce)useSocket, useMap)function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
// Usage
const [theme, setTheme] = useLocalStorage("theme", "light");
Conclusion:
Custom hooks make your code reusable, readable and clean. They help extract repeating logic from components and organize application architecture.