React

useCallback

Basically, useCallback is the same as useMemo, we suggest you take a look at useMemo document first. But useCallback is used for functions only.

useCallback is usually used when you use a function inside other Hooks and list it in the dependencies array. Because each time the component re-renders, if not wrapped inside useCallback, the function will be re-declared, which React will consider as a new variable.

useCallback call signature is similar to useMemo, it takes in 2 arguments:

  • functionToMemorize: the function you want to memorize
  • arrayDependencies: a list of dependencies variables which is used inside the functionToMemorize

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps)

//Call signature
const memoizedCallback = useCallback(functionToMemorize, arrayDependencies)

Basic Usage

function User() {
const [user, setUser] = useState(null)
const [gender, setGender] = useState('male')
const getRandomUser = useCallback(
async() => {
const apiUrl = 'https://randomuser.me/api'
const query = `gender=${gender}&inc=gender,name,picture`
const response = await fetch(`${apiUrl}?${query}`)
.then(r => r.json())
const [user] = response.results || []
setUser(user)
},
// dependencies should include any variables used in the function
[setUser, gender]
)
useEffect(() => {
getRandomUser('male')
}, [getRandomUser])
const handleClickRandom = () => {
getRandomUser('female')
}
const handleCheckChange = (e) => {
setGender(e.target.checked ? "female" : "male")
}
return (
<div>
{!!user ? (
<div>
<img
src={
user.picture ?
user.picture.thumbnail :
`https://ui-avatars.com/api/?name=${user.name}`
}
/>
<span>
{
user.name ?
`${user.name.first} ${user.name.last}` :
"N/A"
}
</span>
</div>
) : ""}
<Button onClick={handleClickRandom}>Random User</Button>
<div>
<input type="checkbox" onChange={handleCheckChange} /> Female User
</div>
</div>
)
}
Previous
useMemo