About
Memoization is a React caching function that caches a computed value.
It
- save the results of computation,
- and reuse these results if it sees the same inputs later.
React memo is the equivalent of shouldComponentUpdate for a class component.
Usage
It will:
- skip:
- computation when the dependency parameters of the memo function are the same
- return the same reference to:
- be able to test for equality.
- not-recompute. If you compute data to be rendered, React will not re-render if the data is the same. (Not that an array or object creation will create each time another reference and will not be the same).
Example Usage
React.Memo wrapping a component
It's a higher-order component React.memo(), meaning it wraps a component
export default React.memo(function myFunctionComponent(props: any): any {
// big computation
return ();
});
UseMemo wrapping an object creation
- Wrapping an array used as data
const sameReference = useMemo(()=>["element1","element2"], [])
UseState as Memo
If the function does not have any dependencies
const [helloWorld] = useState(() => return "Hello World")