Hooks
Motivation
Allow you to use state and effects in functions not classes
Reuse state logic
Have one block of effects for one purpose with clean up and everything
Allows easier reuse of stateful logic often done with patterns like higher-order components and render props.
Basics
Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
Only call Hooks from React function components.
Functions/useCallbacks must be above their use in dependency arrays or else they DONT ACTUALLY CAUSE A RERENDER(cuz hoisting)
All Hooks
useState => See state.md
useEffect => See effect.md
useContext
Still need MyContext.Provider above
If one element of your state relies on the value of another element of your state, then it's almost always best to use
useReducer
Not actually cheaper than defining function by itself. But makes the reference the same for React's equality check if you use the ft in another hook or as a prop to avoid reruns
Unlike useRef, notifies us on change of ref
Can also be equivalent to instance variables in class components. Mutating the
.current
property won’t cause a re-render.Updating a ref is a side effect so it should be done only inside an
useEffect
(oruseLayoutEffect
) or inside an event handler.
useTransition
New in v18
For large UI transitions to mark them as interruptable so typing and stuff doesnt freeze it
Custom Hooks
useWindowWidth
useDebounce
useRandomId
Last updated