How useCallback in React works
In this article we will explain how useCallback is used in React. The built in hook, called useCallback is an optimization hook which basically returns a memoized function that will store the function until the dependencies has changed. So if a component is rendered multiple times, the same function will be returned from useCallback as long as the dependencies hasn't changed.
Related topis:
- Guide on React memo
- Tutorial on useMemo
Code examples
In our first example, we will create a function that are dependent on a state variable. The function will be cached and returned as long as the number hasn't changed.
import { useCallback, useState } from "react"; const MyComponent = () => { const [number, setNumber] = useState(0); const multiplier = useCallback(() => { return number * 2; }, [number]); return <div>{multiplier()}</div>; };
If we change our code a little bit, we will now multiply our number with another number. And this is a common issue, especially when you have many depencencies. If you don't add the dependencies in the array, then the function will not be updated and the value will always be the same until another of the dependencies are updated. Generally, the code editor will show a warning, but not always.
import { useCallback, useState } from "react"; const MyComponent = () => { const [number, setNumber] = useState(0); const [anotherNumber, setAnotherNumber] = useState(0); const multiplier = useCallback(() => { return number * anotherNumber; }, [number]); return <div>{multiplier()}</div>; };
In above code, anotherNumber will potentially have the wrong value since it is not in the dependency array.
With arguments
As with any function, we can also provide arguments to the useCallback hook, and then we need to pass it in when we call the function.
import { useCallback, useState } from "react"; const MyComponent = () => { const [number, setNumber] = useState(0); const multiplier = useCallback( (val: number) => { return number * val; }, [number] ); return <div>{multiplier(10)}</div>; };
Outro
That's it for this short guide on useCallbacks in React. If you want to read about useMemo which is very related, we have a guide here.
Thanks for reading!