CodeBlanks Logo Icon CodeBlanks

useCallback

Learn callback memoization with useCallback.

What is useCallback?

useCallback is a hook that memoizes a function. The component does not create a new function on each render; the same reference is kept. You call it as const handleClick = useCallback(() => { ... }, [deps]).

The value of a stable reference shows up when the child component is memoized. If you pass a new function each render, the child thinks props changed and re-renders unnecessarily. With useCallback you keep the same reference and the child skips. The deps array decides when to recompute; an empty array computes once at mount.

A stable reference

The second parameter of useCallback is the dependency array. This array tells when the function is recreated. An empty array [] creates the function once at mount and keeps it forever.

If you give a variable as a dependency, the function is recreated when that variable changes. For example [count] recreates the function whenever count changes. This balances fresh data with fewer re-renders. Forgetting the dependency array makes React warn you.

Practice Increment with useCallback

Write a Counter component. Hold a count state (useState(0)). Define handleIncrement with useCallback; dependency array is [count]. The component returns <Text>{count}</Text>.

Starter code

App.js
// Import useState and useCallback

function Counter() {
  // Initialize count state
  // Define handleIncrement with useCallback; deps is [count]

  return <Text>{count}</Text>;
}

Sample solution

App.js
import { useState, useCallback } from "react";
import { Text } from "react-native";

function Counter() {
  const [count, setCount] = useState(0);
  const handleIncrement = useCallback(() => {
    setCount(count + 1);
  }, [count]);
  return <Text>{count}</Text>;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 The useCallback call

Question
const handleClick = ____(() => { console.log('tıklandı'); }, []);
Answer
const handleClick = useCallback(() => { console.log('tıklandı'); }, []);

Explanation: useCallback keeps the function with a stable reference.

2 What does useCallback return?

App.js
const fn = useCallback(() => {}, []);
  • A function Correct answer
  • A state
  • A value
  • An array

Explanation: useCallback returns a function.

3 Match each piece to its role

Term Meaning
useCallback Stores a function
deps array Recompute condition
stable reference Skips the child
empty array Once at mount

All lessons in Intermediate