🔁 useCallback in React.js – Small Hook, Big Performance Impact When building React applications, unnecessary re-renders can silently affect performance. One hook that helps control this is useCallback. What is useCallback? useCallback is a React hook that memoizes a function, meaning React will reuse the same function reference between renders unless its dependencies change. This is especially useful when passing functions to child components, because React normally creates a new function on every render. That can cause child components to re-render even when nothing actually changed. Example: import { useState, useCallback } from "react"; function Counter() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log("Button clicked"); }, []); return ( <div> <button onClick={handleClick}>Click Me</button> <p>{count}</p> </div> ); } In this example, handleClick keeps the same function reference across renders because of useCallback. Why it matters: ✔ Prevents unnecessary re-renders ✔ Improves performance in optimized components ✔ Useful with React.memo When to use it? Use useCallback when: Passing functions to memoized components Working with expensive re-renders Optimizing large React applications ⚠️ But remember: Not every function needs useCallback. Overusing it can actually make code harder to maintain without real performance benefits. 💡 Understanding hooks like useCallback helps in writing cleaner and more optimized React applications. #ReactJS #WebDevelopment #JavaScript #FrontendDevelopment #ReactHooks #Coding
React useCallback Hook for Performance Optimization
More Relevant Posts
-
⚛️ React Tip: When Should You Use useCallback? While working on React applications, one common performance issue developers face is unnecessary component re-renders. One hook that often comes up in this discussion is useCallback. But many developers (including me earlier) either overuse it or use it incorrectly. So here’s a simple way to understand it. 🔹 What does useCallback do? `useCallback` memoizes a function. This means React will reuse the same function instance unless its dependencies change. Example 👇 const handleClick = useCallback(() => { console.log("Button clicked"); }, []); Without `useCallback`, a new function is created every time the component re-renders. Most of the time this isn’t a problem. But it becomes important when passing functions to memoized child components. 🔹 Example scenario Imagine a parent component passing a function as a prop to a child component wrapped with `React.memo`. If the function reference changes on every render, the child component will also re-render unnecessarily. Using `useCallback` helps keep the function reference stable, preventing those extra renders. 🔹 When should you actually use it? ✅ When passing callbacks to memoized components ✅ When the function is a dependency in another hook ✅ When optimizing large component trees ⚠️ When NOT to use it: • For every function in your component • When there is no performance issue • Just because someone said it improves performance 💡 One important lesson I’ve learned: Optimization should be intentional, not automatic. React already does a lot of work under the hood. Use hooks like `useCallback` only when they actually solve a problem. Curious to hear from other developers 👇 Do you use `useCallback` often, or do you prefer optimizing only after profiling? #reactjs #frontenddevelopment #javascript #webdevelopment #reacthooks #softwareengineering #coding
To view or add a comment, sign in
-
-
A very common React mistake I see developers make: Mutating State When I was learning React, one concept that changed the way I write code was this rule: 👉 React state must never be mutated.its always immutable. But why? React does not deeply compare objects or arrays when state updates. Instead, it performs a reference(memory) comparison. That means React checks: Old State === New State ? If the reference is the same, React assumes nothing changed and skips re-rendering. Example of a mistake: cart.push(product) // ❌ Mutating state setCart(cart) Here we modified the same array in memory, so React may not detect the change because the memory location is same.so no re-render..no UI update. The correct approach is immutability: setCart([...cart, product]) // ✅ Creating a new array Now React sees a new reference, triggers reconciliation, and updates the UI correctly. 💡 Why React prefers immutability: • Faster change detection • Predictable state updates • Easier debugging • Better performance This small concept explains why patterns like: map() filter() spread operator (...) are used so frequently in React. because all this returns new object or array... Understanding this helped me write cleaner and more reliable React components. What React concept took you the longest to understand? 🤔 #React #Frontend #JavaScript #WebDevelopment #ReactJS
To view or add a comment, sign in
-
-
What Runs First in React? Most React developers know what useEffect, useMemo, and useCallback do individually. Far fewer know the exact order they execute in. And that gap causes bugs that are surprisingly difficult to trace. Here is the definitive execution order on first mount: -> Step 1: Rendering JSX React runs the function body of your component first. JSX is evaluated. console.log inside the return runs here. This is the render phase. -> Step 2: useMemo runs during render useMemo executes synchronously during the render phase, not after it. If you have an expensive computation wrapped in useMemo, it runs as part of building the component output. This is why useMemo can be used to compute values that are needed in the JSX itself. -> Step 3: useEffect runs after render After the component has rendered and the DOM has been updated, useEffect fires. It is intentionally deferred. This is where API calls, subscriptions, and side effects belong because they should not block the render. -> useCallback is different from all of them useCallback does not run during mounting. It stores a function reference. That function only executes when it is explicitly called. In the example on the right, increment only logs when you actually call increment(). The final order: Rendering JSX, then useMemo, then useEffect. Why this matters in practice: If you expect useEffect to run before useMemo, your state update will not be available when useMemo computes. If you expect useCallback to run automatically, your side effect will never fire. Getting the order wrong means working with stale data and writing code that behaves differently than you intended. Understanding execution order is not academic. It is the difference between components that behave predictably and ones that produce subtle timing bugs you spend hours debugging. Did you know the exact execution order before seeing this or did it surprise you? #React #ReactHooks #FrontendDevelopment #JavaScript #WebDevelopment #Developers
To view or add a comment, sign in
-
-
🚀 Understanding Class Components in React One concept that helped me understand how components work internally was Class Components. Before Hooks became popular, class components were the primary way to manage state and lifecycle methods in React applications. A class component is simply a JavaScript class that extends React.Component and must contain a render() method that returns JSX. Example: import React, { Component } from "react"; class Welcome extends Component { render() { return <h1>Hello World</h1>; } } export default Welcome; In class components: 🔹 Props are accessed using this.props 🔹 State is managed using this.state 🔹 State updates are done with this.setState() 🔹 Lifecycle methods like componentDidMount() allow us to run code when the component mounts, updates, or unmounts. Example with state: class Counter extends Component { state = { count: 0 }; increase = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <button onClick={this.increase}> {this.state.count} </button> ); } } Today, most developers prefer Functional Components with Hooks like useState and useEffect, but understanding Class Components is still valuable because: ✅ Many legacy React projects still use them ✅ They help you understand React's lifecycle deeply ✅ Some interview questions still cover them Learning both approaches gives you a stronger foundation in React. Sometimes, understanding the old way helps you appreciate the modern way even more. #React #FrontendDevelopment #JavaScript #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
I struggled with this React concept more than I expected… 👇 👉 Why are my API calls running twice? ⚙️ What you’ll notice You open your network tab and suddenly see this: api/me → called twice api/roles → called twice api/permissions → called twice Just like in the screenshot 👇 Same request, duplicated… again and again. ⚙️ What’s actually happening In React (development mode), if your app is wrapped in Strict Mode, React will run effects twice on purpose. useEffect(() => { fetch("/api/users") .then(res => res.json()) .then(setUsers); }, []); Even though it looks like it should run once… it doesn’t (in dev). 🧠 What’s going on under the hood React basically does a quick cycle: mount → unmount → remount Why? To catch hidden side effects To check if cleanup is handled properly To make sure your logic doesn’t break on re-renders So if your API call runs twice, React is just making sure your code can handle it. 💡 The important part This only happens in development Production behaves normally (runs once) Your side effects should be safe to run multiple times 🚀 Final thought If your network tab looks “noisy” like the screenshot, it’s not React being broken — it’s React being careful. And once you understand this, debugging becomes a lot less confusing. #React #Frontend #JavaScript #WebDevelopment #ReactJS #SoftwareEngineering
To view or add a comment, sign in
-
Why do we need to call 'super(props)' in the constructor of a React component? JavaScript classes aren't magic. They are just syntactic sugar over prototypes. If you are still using (or have used) Class Components in React, you have likely typed 'super(props)' a thousand times. But do you actually know what happens if you forget it? In JavaScript, you cannot use the keyword 'this' in a constructor until you have called the parent constructor. Since your component extends 'React.Component', calling 'super()' is what actually initializes the 'this' object. If you try to access 'this.state' or 'this.props' before that call, JavaScript will throw a ReferenceError and crash your app. But why pass 'props' into it? React sets 'this.props' for you automatically after the constructor runs. However, if you want to access 'this.props' inside the constructor itself, you must pass them to 'super(props)'. If you just call 'super()', 'this.props' will be undefined until the constructor finishes execution. Most of us have moved to Functional Components where this isn't an issue. But understanding these fundamentals is what separates a developer who just writes code from one who understands the runtime. #ReactJS #Javascript #SoftwareEngineering #WebDevelopment #Coding #ProgrammingTips
To view or add a comment, sign in
-
⚛️ In React, these three onClick patterns look almost identical… but behave very differently. onClick={handleAddItem} onClick={handleAddItem(item)} onClick={() => handleAddItem(item)} At a glance they seem similar, but the execution timing is completely different. 🔹 onClick={handleAddItem} Passes the function reference → runs only when the click event occurs. 🔹 onClick={handleAddItem(item)} Executes immediately during render, not on click. This can lead to unexpected behavior like unnecessary API calls or extra re-renders. 🔹 onClick={() => handleAddItem(item)} Creates a callback function that runs on click and allows you to pass parameters. ✅ Rule of thumb • No parameters → onClick={handleAddItem} • Need parameters → onClick={() => handleAddItem(item)} • Avoid → onClick={handleAddItem(item)} 💡 One more interesting detail Arrow functions create a new function on every render. In most cases this is perfectly fine. However, in large lists or memoized components (React.memo), this can sometimes trigger unnecessary re-renders. That’s why some developers use useCallback or pre-defined handlers for optimization. 👨💻 How do you usually handle this in your projects? Arrow functions, useCallback, or another pattern? #React #JavaScript #FrontendDevelopment
To view or add a comment, sign in
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers understand closures in JavaScript… but get confused when it comes to React. Question: What will be the output of this code? Example 👇 import React, { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { console.log(count); }, 1000); }; return ( <> <button onClick={handleClick}> Click </button> <button onClick={() => setCount(count + 1)}> Increase Count ({count}) </button> </> ); } Now imagine: You click the button 3 times quickly and count updates each time What will be logged after 1 second? Answer 👇 It will log the SAME value multiple times ❌ Why? Because of closure. The setTimeout callback captures the value of count at the time handleClick was created. This is called a “stale closure”. Correct approach ✅ useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, [count]); Or use useRef for latest value. Tip for Interview ⚠️ Closures + async code can lead to stale state bugs in React. Good developers know closures. Great developers know how closures behave in React. #ReactJS #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks
To view or add a comment, sign in
-
-
🔥 Why useEffect Runs Twice in React Strict Mode If you’ve seen this while developing with React: JSX code : useEffect(() => { console.log("Effect ran"); }, []); You expect this to run once. But in development, the console shows: Effect ran Effect ran So… is React broken? Not really. 🧠 What’s Actually Happening When React Strict Mode is enabled, React intentionally runs some lifecycle logic twice in development. This includes useEffect. Why? Because React is checking if your effects are safe and predictable. 🔍 What React Is Testing React wants to detect bugs like: Side effects that are not cleaned up Code that relies on running only once Hidden memory leaks To do that, React: 1️⃣ Mounts the component 2️⃣ Runs the effect 3️⃣ Immediately unmounts it 4️⃣ Mounts it again If your cleanup logic is correct, everything still works. ✅ Example with Cleanup JSX code useEffect(() => { const id = setInterval(() => { console.log("running"); }, 1000); return () => clearInterval(id); }, []); This ensures no leftover side effects. 🎯 Important Note This only happens in development. Production builds run effects normally. #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
React tip I wish someone told me earlier 👇 React Redux vs Redux Thunk. I was using both without actually knowing why. Just copying, pasting, and hoping it works. So I sat down, broke it apart, and here's what actually clicked: ━━━━━━━━━━━━━━━━━━━━ 🔵 USE REACT REDUX WHEN... ━━━━━━━━━━━━━━━━━━━━ ✓ You want to read state in a component → useSelector ✓ You want to fire an action from a component → useDispatch ✓ You want your UI to update when state changes If your action is just a plain object like { type: 'SET_USER', payload: user } React Redux alone is enough. ━━━━━━━━━━━━━━━━━━━━ 🟢 ADD REDUX THUNK WHEN... ━━━━━━━━━━━━━━━━━━━━ ✓ You need to call an API before updating state ✓ You need to dispatch multiple actions in order ✓ You need logic before deciding what to dispatch ✓ You need to read current state inside an action creator The moment your action needs to DO something before it reaches the reducer — that's Thunk's job. ━━━━━━━━━━━━━━━━━━━━ One rule that made it simple for me: ━━━━━━━━━━━━━━━━━━━━ No async? → React Redux is enough. Async anywhere? → Add Thunk. Login, fetching data, submitting a form — that's async. That's literally every real app. So yes, you'll use both. But now you know WHY — not just because a tutorial said so. If you're learning Redux and it feels overwhelming, I hope this helps even a little. 🙌 Will keep sharing whatever I learn along the way. #ReactJS #Redux #ReduxThunk #JavaScript #Frontend #LearningInPublic #WebDevelopment
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development