React Hooks Flashcards
useReducer( )
What is this an alternative to?
What are its inputs?
What are its outputs?
When should you use it?
How does it optimize performance?
- Alternative to useState.
- Accepts reducer type (state, action) => newState & returns current state + a dispatch method
- WHEN TO USE: used when you have complex state logic that involves multiple sub-values OR when the next state depends on the previous one.
- Optimizes performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.
Explain what the init function does in
useReducer( reducerFn, defaultState, init );
Briefly describe what this example does.
Lazy initialization can be used for the third parameter.
Code snippet:
- Reset button sends a payload with a ‘state’ value and resets the UI to that ‘state’ value.
- This is handy for resetting the state later in response to an action.
useCallback( )
- What does it return?
- What do you pass it?
- When does it change?
- Why is it used?
- Returns a memoized callback.
- Passes an inline callback and an array of dependencies.
- Only changes when dependencies have changed.
- Used to optimize child components to prevent unnecessary renders.
What is a memoized callback?
An optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
useCallback( fn, deps ) is equivalent to useMemo( ( ) => fn, deps ).
True!
useMemo( )
- What does it return?
- What do you pass it?
- When does it re-compute a value?
- Why would you use it? To avoid….
- What should you NOT use in it?
- What happens if no dependency array is provided?
- BONUS! Something something blah blah blah on semantic guarantee.
- Returns memoized value.
- Pass a ‘create’ function and an array of dependencies.
- Only re-computes the memoized value when one of the dependencies changed.
- Avoids expensive calculations on every render.
- Function passed to useMemo runs during rendering don’t do anything that you wouldn’t normally do while rendering (i.e. useEffect’s side effect variable).
- If no dependency array is provided, a new value will compute on every render.
-
You may rely on useMemo as a performance optimization, not as a semantic guarantee.
- Read more here.
const = refContainer = useRef(initialValue);
Returns a _________ object.
How would you access the input value that refContainer is assigned to?
Does this persist through the full lifetime of the component?
How do you access the DOM? What variable would you assign refContainer to?
What is it also useful for?
- Returns a mutable ref object with a current property.
- refContainer.current.value will provide the input value.
- The returned object will persist for the full lifetime of the component.
- A common use case is to access a child imperatively.
- You can pass the ref object in react to access the DOM. < div ref = { refContainer } />
- Useful for more than just DOM ref assignments. It’s useful for keeping any mutable value around, i.e. instance fields in classes.
- useRef creates a plain JS object and will give you the same ref object on every render.
- Will not notify you, and .current property will not cause a re-render, if you want to be notified when the ref object attaches/detaches from the DOM node, you may want to use a callback ref
useImperativeHandle( ref, createHandle, [deps] );
What should be used with this hook?
What cases should you avoid?
Should be used with forwardRef
Should avoid using imperative code when using refs.
The signature is identical to useEffect, but it fires synchronously after all DOM mutations.
Use this to read layout from the DOM and synchronously re-render.
useDebugValue( value );
useDebugValue can be used to display a label for custom hooks in React DevTools.
Defer formatting debug values
We don’t recommend adding debug values to every custom Hook. It’s most valuable for custom Hooks that are part of shared libraries.
useDeferredValue( value )
useDeferredValue accepts a value and returns a new copy of the value that will defer to more urgent updates.
If the current render is the result of an urgent update, like user input, React will return the previous value and then render the new value after the urgent render has completed.
This hook is similar to user-space hooks which use debouncing or throttling to defer updates. The benefits to using useDeferredValue is that React will work on the update as soon as other work finishes (instead of waiting for an arbitrary amount of time), and like startTransition, deferred values can suspend without triggering an unexpected fallback for existing content.
Memoizing deferred children
useDeferredValue only defers the value that you pass to it. If you want to prevent a child component from re-rendering during an urgent update, you must also memoize that component with React.memo or React.useMemo:
What does memoizing the children tell React?
Memoizing the children tells React that it only needs to re-render them when deferredQuery (see image) changes and not when query changes. This caveat is not unique to useDeferredValue, and it’s the same pattern you would use with similar hooks that use debouncing or throttling.
generating unique IDs that are stable across the server and client, while avoiding hydration mismatches.
useId is NOT for generating keys in a list. Keys should be generated from your data.
useId is not supported in CSS selectors or APIs like querySelectorAll.
useId supports an identifierPrefix to prevent collisions in multi-root apps. To configure, see the options for hydrateRoot and ReactDOMServer.