The useCallback hook memoizes the function itself, not its return value. useCallback caches the function reference
A function declared inside a component gets re-created on every render, similar to a variable. The difference is, it gets rendered with a different reference every time. So,
- A useEffect dependent on this function will execute again on each render.
- A similar thing happens with child components.
A useEffect dependent on this function will execute again on each render:
import React, { useState, useEffect, useCallback } from 'react'; // Parent Component const ParentComponent = () => { const [count, setCount] = useState(0); const [text, setText] = useState(""); // Function declared inside the component const handleClick = () => { setCount(count + 1); }; // useEffect depending on handleClick useEffect(() => { console.log("handleClick changed, running useEffect"); }, [handleClick]); return ( <div> <button onclick="{handleClick}">Increment Count</button> <p>Count: {count}</p> <childcomponent handleclick="{handleClick}"></childcomponent> </div> ); }; // Child Component const ChildComponent = React.memo(({ handleClick }) => { console.log("ChildComponent re-rendered"); return <button onclick="{handleClick}">Child Increment</button>; }); export default ParentComponent;
A similar thing happens with child components:
When we have a component with expensive or "slow" rendering logic as a child of another component, every time the parent component renders, all of its children also re-render.
To prevent these unnecessary re-renders, we can use React.memo. This higher-order component caches the child component, ensuring that it only re-renders if its props actually change. However, there’s a subtle catch when passing functions as props, which causes the child to re-render even when it shouldn’t.
The Problem with Function References
Imagine we have a SlowComponent as a child of App. In App, we have a state that changes on button click, triggering a re-render of App. Although we’re not changing SlowComponent's props, it still re-renders on every click.
Why? On each render, the handleClick function is re-created with a new reference, which React interprets as a changed prop, causing SlowComponent to re-render. To fix this, we use the useCallback hook to cache the function's reference across renders.
Solution with useCallback
By wrapping handleClick inside useCallback, we tell React to only re-create it when specific dependencies change. Here’s the syntax:
const cachedFn = useCallback(fn, [dependencies]);
- fn: This is the function definition you want to cache. It can accept arguments and return any value.
- dependencies: This is an array of dependencies. React will re-create fn if any dependency changes. On the first render, React creates and caches the function. On subsequent renders, as long as the dependencies haven’t changed, the cached function is returned, ensuring it has a stable reference.
Applying useCallback in Our Example
Let’s take a look at how we’d use useCallback to optimize our App component:
import React, { useState, useCallback } from "react"; const App = () => { const [count, setCount] = useState(0); const [value, setValue] = useState(""); // Wrapping handleClick with useCallback to cache its reference const handleClick = useCallback(() => { setValue("Kunal"); }, [setValue]); return ( <div> <button onclick="{()"> setCount(count + 1)}>Increment Count</button> <p>Count: {count}</p> <slowcomponent handleclick="{handleClick}"></slowcomponent> </div> ); }; const SlowComponent = React.memo(({ handleClick }) => { // Intentially making the component slow for (let i = 0; i Click me in SlowComponent; }); export default App;
When to use useCallback
- When you have event handlers defined for an element inside your component, wrap them inside a useCallback to avoid unnecessary re-creations of event handlers.
- When you call a function inside a useEffect, you usually pass the function as a dependency. To avoid using useEffect unnecessarily on every render, wrap the function definition inside a useCallback.
- If you are writing a custom hook, and it returns a function, it is recommended to wrap it inside a useCallback. So, there's no need for the users to worry about optimizing the hook – rather, they can focus on their own code.
The above is the detailed content of Understanding useCallback in Reactjs. For more information, please follow other related articles on the PHP Chinese website!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor
