Hooks
Motivation
Basics
All Hooks
const value = useContext(MyContext);function MeasureExample() { const [height, setHeight] = useState(0); const measuredRef = useCallback(node => { if (node !== null) { setHeight(node.getBoundingClientRect().height); } }, []); return ( <> <h1 ref={measuredRef}>Hello, world</h1> <h2>The above header is {Math.round(height)}px tall</h2> </> ); }
- Your app must still work perfectly well (maybe a bit slow though) if `useMemo` calls your callback on every render. - Introduces overhead, but for expensive pure computationsfunction TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` points to the mounted text input element inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
const [isPending, startTransition] = useTransition(); setInputValue(input); startTransition(() => { setSearchQuery(input); });
Custom Hooks
Last updated