
What is React's useCallback?
Requirements
- React.js (16.8 or newer)
Introduction
React's , much like memo and useMemo, is used to optimize the rendering of given React function component by memoizing it.Although every one of them have different use cases.
Problem
Let's say you have this component:
import React, { useState, memo } from "react"; const Child = memo(function (props) { // This is rendering once return <h1>I'm a child component</h1>; }); export default function App() { const [localState, setLocalState] = useState(0); function aFunction() {} return ( <div> <Child func={aFunction} /> <h1>LocalState: {localState}</h1> <button onClick={() => setLocalState(localState + 1)}> Change local state </button> </div> ); }
Differently from the memo example, in this scenario the component have a
prop passed to it, even if the prop doesn't change, it re-renders breaking
functionality as the value passed (
) is being re-created at every parent render. So
identifies the prop change and forces
re-render.
Solution
To avoid re-rendering we can use the useCallback hook on the prop value, before including as a prop in the component as such:
import React, { useState, memo, useCallback } from "react"; const Child = memo(function (props) { // This is rendering once return <h1>I'm a child component</h1>; }); export default function App() { const [localState, setLocalState] = useState(0); function aFunction() {} const memoizedFunc = useCallback(aFunction, []); return ( <div> <Child func={memoizedFunc} /> <h1>LocalState: {localState}</h1> <button onClick={() => setLocalState(localState + 1)}> Change local state </button> </div> ); }
What makes the component re-render is that at every state change the
function forces
to be recreated, then the
component receives that "new" function and re-renders. The
hook will make the component avoid re-rendering by memoizing
, so if the function doesn't change,
component won't re-render.
TLDR
basically memoizes the function passed as the first argument.
Additional Resources
Related Posts
- What is React's useCallback?2021-09-02
- What does the useReducer hook do2023-01-05
- How to use Debounce in Reactjs?2023-01-04
- What is React's useMemo2021-09-02
- What is React's Context API?2021-08-28
- React - What is Prop Drilling?2021-08-28
- React - Controlled Vs Uncontrolled2021-08-27