✅ Logical Operators in JavaScript – Complete Guide with Real Examples

Image
πŸ“Œ Introduction Logical operators help you combine conditions, control flow, and make decisions in JavaScript. In this guide, you’ll learn how to use && , || , and ! effectively with examples and real-world use cases. πŸ” What Are Logical Operators? Logical operators return a boolean value ( true or false ) and are used to evaluate expressions, especially within conditions like if statements. Operator Name Example Description && Logical AND a && b Returns true if both conditions are true || Logical OR a || b Returns true if either condition is true ! Logical NOT !a Reverses the boolean value ✅ 1. Logical AND ( && ) const age = 25; const isCitizen = true; if (age > 18 && isCitizen) { console.log("You can vote!"); } Short-circuiting: If the first condition is false, the second one isn’t evaluated. ✅ 2. Logi...

🧠 Mastering useCallback in React: Boost Performance by Preventing Unnecessary Re-Renders

Mastering useCallback in React

πŸ” Introduction: Why Care About useCallback in React?

In modern React development, optimizing performance is critical — especially as your app scales. Ever encountered laggy UI or unnecessary component re-renders when passing functions as props? That’s where the useCallback hook steps in.

The useCallback hook is often misunderstood or misused, yet it plays a crucial role in ensuring your components don't re-render more than they need to. In this post, we’ll break down everything you need to know about useCallback — with code examples, real-world analogies, and answers to frequently asked developer questions.

πŸ”§ What is useCallback in React?

useCallback is a React Hook that returns a memoized version of a callback function. This means the function won’t be recreated on every render, unless its dependencies change.

const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

This becomes essential when you’re passing functions to child components that rely on reference equality to avoid re-renders (like those wrapped in React.memo).

πŸ§ͺ Real-World Analogy: Think of useCallback as a Phone Number

Imagine calling your friend every day. If their phone number changes daily, you’d always need to ask them for the new number. But if their number stays the same, calling is efficient.

Similarly, if your function reference changes every render, React thinks something new happened and re-renders child components. useCallback ensures the "phone number" (function reference) stays the same unless the logic needs to change.

❓Common Developer Questions About useCallback

✅ Why Do We Use useCallback?

  • To prevent unnecessary re-renders in memoized child components.
  • To maintain reference stability of callback functions.
  • To improve performance when passing functions as props.

✅ When Should You Use useCallback?

  • When passing a function to a child component wrapped in React.memo.
  • When the function is expensive to recreate or causes re-renders.
  • When dependencies don’t change often.

Avoid using it just for the sake of it — it has memory overhead.

πŸ‘¨‍πŸ’» Example: Without useCallback

const Parent = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    console.log("Clicked!");
  };

  return (
    <>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <Child onClick={handleClick} />
    </>
  );
};

const Child = React.memo(({ onClick }) => {
  console.log("Child re-rendered");
  return <button onClick={onClick}>Click Me</button>;
});

✅ Example: With useCallback

const Parent = () => {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    console.log("Clicked!");
  }, []);

  return (
    <>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <Child onClick={handleClick} />
    </>
  );
};

🧠 useCallback vs useMemo: What’s the Difference?

HookPurposeReturns
useCallbackMemoize functionThe same function reference
useMemoMemoize value/resultThe result of a computation
const memoizedFn = useCallback(() => compute(a, b), [a, b]);
const memoizedValue = useMemo(() => compute(a, b), [a, b]);

πŸš€ Performance Optimization With React DevTools

Use React DevTools Profiler to:

  • Inspect component re-renders.
  • Confirm memoization effectiveness.
  • Analyze rendering frequency and time.

Steps:

  1. Install React DevTools Chrome extension.
  2. Open Profiler tab.
  3. Wrap components in React.memo and monitor re-renders.
  4. Add useCallback and see performance improve.

🧭 Best Practices for useCallback

  • ✅ Use when passing functions to React.memo components.
  • ✅ Avoid overuse — it adds complexity and consumes memory.
  • ✅ Keep dependency array accurate — incorrect dependencies cause stale closures.
  • ✅ Don’t use it with inline functions you don’t pass down.
  • ✅ Combine with useMemo when needed for derived values and callbacks.

πŸ”‚ Avoiding Function Re-Creations: The Big Picture

<ChildComponent onClick={() => doSomething()} /> // bad

Instead:

const handleClick = useCallback(() => doSomething(), []);
<ChildComponent onClick={handleClick} /> // good

This tiny change can drastically improve performance in large applications.

πŸ—️ Dealing With useState and useCallback Together

const [count, setCount] = useState(0);

const increment = useCallback(() => {
  setCount((prev) => prev + 1); // Correctly uses functional update
}, []);

πŸ’‘ Bonus: Optimize Expensive Calculations With useMemo + useCallback

const expensiveValue = useMemo(() => computeHeavyLogic(input), [input]);

const handleClick = useCallback(() => {
  console.log(expensiveValue);
}, [expensiveValue]);

πŸ”„ Summary Table: useCallback Essentials

FeatureDescription
GoalMemoize callback functions
PreventsUnnecessary re-renders
Ideal use casePassing callbacks to child components
Reference equalityMaintained unless deps change
Common mistakeUsing without React.memo context
Performance toolReact DevTools Profiler
vs useMemouseCallback memoizes functions, useMemo memoizes values

πŸ“£ Final Thoughts

useCallback is a powerful yet misunderstood tool in React’s optimization arsenal. While you shouldn’t overuse it, when used correctly — especially with React.memo — it can help reduce re-renders and speed up your app.

Use this post as a cheat sheet whenever you’re deciding whether or not to memoize a function. And always test your assumptions using React DevTools Profiler.

πŸ”— Related Resources

πŸ“Œ Keywords

useCallback in React, React performance optimization, memoized callback, React Hooks, prevent unnecessary re-renders, function reference stability, useCallback vs useMemo, React DevTools, optimize child components, React useCallback example

Comments

Popular posts from this blog

How to Fix npx tailwindcss init Error: “Could Not Determine Executable to Run”

πŸš€ “JavaScript Debounce Made Simple + Live Example!”

πŸ› ️ How to Create a React App with Vite and Tailwind (Beginner Guide)