ReactQuestion 04 of 28
How can you write custom hooks?
Answer out loud or in your head first, then compare.
Answer
A custom hook is a function whose name starts with use and that can call other hooks.
JavaScript
function useWindowWidth() {
const [width, setWidth] =
useState(window.innerWidth);
useEffect(() => {
const handler = () =>
setWidth(window.innerWidth);
window.addEventListener(
"resize",
handler
);
return () =>
window.removeEventListener(
"resize",
handler
);
}, []);
return width;
}Then:
JavaScript
const width = useWindowWidth();It lets you extract logic and reuse it.
To be precise:
A custom hook shares logic, but not automatically the same state. Each use of the hook usually has its own state.
How did it go? Be honest — “Not yet” puts the question on your review list.