React Hooks Flashcards
when does useEffect run?
By default, effects run after every completed render, but you can choose to fire them only when certain values have changed. This is where the dependency array comes in. In this we put the values that, if changed, fire off useEffect.
Although useEffect is deferred until after the browser has painted, it’s guaranteed to fire before any new renders. React will always flush a previous render’s effects before starting a new update.
useContext
this function is passed the context object as defined in the closest Context.provider wrapped components ‘value’ prop.
A component calling useContext will always re-render when the context value changes. If re-rendering the component is expensive, you can optimize it by using memoization.
useReducer
accepts a reducer and initial state as arguments. switch statement based on action types, similar to redux. returns an array that we de-structure as [state, dispatch]
useCallback
returns a memoized callback. param is a callback that calls the function we want to memoize.
Array of deps is not passed as args to the cb. every value referenced inside the cb should also appear in the dependencies array.
if no array is provided, a new value will be computed on every render.
const memoizedCallback = useCallback( () => { doSomething(a, b); }, [a, b], );
useMemo
returns a memoize value. useMemo will only recompute the memoize val when one of the dependencies has changed.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
useRef
useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
const refContainer = useRef(initialValue);
Essentially, useRef is like a “box” that can hold a mutable value in its .current property.
Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
useImperativeHandle
useImperativeHandle customizes the instance value that is exposed to parent components when using ref.
allows parent components to reference child refs
a parent component that renders would be able to call inputRef.current.focus().
useDebugValue
can be used to display a label for custom hooks in React DevTools.
// Show a label in DevTools next to this Hook
// e.g. “FriendStatus: Online”
within component:
useDebugValue(isOnline ? ‘Online’ : ‘Offline’);