Here's the translation:
Memoization is the process of storing the results of computations between component reloads.
It can be useful when a large list of elements is passed to a component, and filtering/creating them requires significant resources. Computing within the component code block would result in the same function being executed on every component render. Memoization ensures that the function is executed only when the values of specified variables change.
Another application scenario is when a value or function is passed to the dependency array
of another hook. If these values or functions do not change with every render, the hooks to which they are passed won't be triggered again.
Hooks used for memoization include:
useMemo
- saves the value of a function execution
const Component: React.FC = ({ list, ...props }) => { const myList = useMemo(() => { return list.map(el => someComplexOperation(el)); }, [list]); // changes in the variables specified here will cause the useMemo function to trigger again and overwrite the myList value return <div>{myList}</div> }
useCallback
- saves the function itself, not the result of its execution. Otherwise, the function would be re-declared on every render
const Component: React.FC = ({ list, ...props }) => { const getCalculatedList = useCallback(() => { return props.list.map(el => someComplexOperation(el)); }, [list]); // changes in the variables specified here will cause the useCallback function to trigger again and create a new getCalculatedList function return <div>{getCalculatedList()}</div> }
Another example of momeization is to use memo
function on component declaration. It allows component to not rerender when it's props
didn't change. It accepts a component and optional comparison function of old and new props
:
interface Props { myProp: string } const MyComponent: React.FC<Props> = ({myProp}) => { ... }; const didPropsChange = (oldProps: Props, newProps: Props) { .... } const MemoizedComponent = memo(MyComponent, didPropsChange) // didPropsChange is optional - shallow comparison of props is made by default
Docs about memo
are available here.