Advanced Hook -

return results, isLoading ;

const FancyInput = forwardRef((props, ref) => const inputRef = useRef(); useImperativeHandle(ref, () => ( focus: () => inputRef.current.focus(), clear: () => inputRef.current.value = ''; , shake: () => /* animation logic */ )); return <input ref=inputRef ...props />; ); // Parent usage: const ref = useRef(); <FancyInput ref=ref /> ref.current.shake(); advanced hook

This custom hook elegantly solves the "compare current vs previous" problem without extra state. Sometimes a parent component needs to call a child’s method (e.g., focus an input, reset a form, start an animation). While React discourages imperative code, advanced cases justify it. It allows you to extract component logic into

This keeps the child’s internal implementation private while exposing only the necessary imperative API. The pinnacle of advanced hooks is creating your own. A custom hook is a JavaScript function whose name starts with use and may call other hooks. It allows you to extract component logic into reusable, testable units. Example: useDebouncedSearch function useDebouncedSearch(query, delay = 300) const [results, setResults] = useState([]); const [isLoading, setIsLoading] = useState(false); useEffect(() => if (!query) return; const handler = setTimeout(async () => setIsLoading(true); const data = await searchAPI(query); setResults(data); setIsLoading(false); , delay); return () => clearTimeout(handler); , [query, delay]); delay = 300) const [results