Hooks Overview
Hooks are functions starting with use that let you opt into React features (state, effects, context, refs) from inside a function component. Custom hooks compose the built-ins into reusable, named behaviour.
Built-ins + a custom hook
EXAMPLE
import { useState, useEffect, useRef, useReducer, useMemo, useCallback, useContext } from 'react';
// useState — local state
const [count, setCount] = useState(0);
// useEffect — side effects + cleanup
useEffect(() => {
const id = setInterval(() => setCount(c => c + 1), 1000);
return () => clearInterval(id);
}, []);
// useRef — mutable value, no re-render
const inputRef = useRef(null);
// useMemo / useCallback — memoise
const expensive = useMemo(() => heavyCalc(items), [items]);
const onSave = useCallback(() => api.save(data), [data]);
// useReducer — complex transitions
const [state, dispatch] = useReducer(reducer, initialState);
// useContext — read from a provider above
const theme = useContext(ThemeContext);
// Custom hook — pulls logic out of the component
function useDebounce(value, ms = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const t = setTimeout(() => setDebounced(value), ms);
return () => clearTimeout(t);
}, [value, ms]);
return debounced;
}
// Usage
function SearchBox() {
const [q, setQ] = useState('');
const debouncedQ = useDebounce(q, 250);
useEffect(() => { if (debouncedQ) api.search(debouncedQ); }, [debouncedQ]);
return <input value={q} onChange={e => setQ(e.target.value)} />;
}
Why it matters
Custom hooks are how teams scale React. Promote any “state + effects + memoising” pattern that appears in two components into a named hook — reusable, testable, type-safe.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// Hooks let function components have state and side effects. // useState, useEffect, useRef, useMemo, useCallback, useContext, useReducer, …Try it Yourself »
Discussion
Loading…