Custom HooksIntermediate
1Question 1 of 1
javascriptHow do Custom Hooks encapsulate stateful logic and promote code reuse?
Explanation & Concept
A Custom Hook is a JavaScript function whose name starts with `use` and that can call other React hooks. Custom hooks do not share state; they share **stateful logic**.
Code Example
javascript
import { useState, useEffect } from "react";
// Custom hook to detect window dimensions
export function useWindowDimensions() {
const [dimensions, setDimensions] = useState({
width: typeof window !== "undefined" ? window.innerWidth : 0,
height: typeof window !== "undefined" ? window.innerHeight : 0
});
useEffect(() => {
function handleResize() {
setDimensions({ width: window.innerWidth, height: window.innerHeight });
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return dimensions;
}
// In any component:
// const { width } = useWindowDimensions();How It Works & Key Takeaways
Any component can now consume window dimensions reactively with a single line of code, keeping resize listener cleanup isolated.
Mock Test · 1 Questions · Optional
Ready for Component Lifecycle?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions