DEV Community

Jayashree
Jayashree

Posted on

React Hooks Explained: useMemo, useCallback, and useNavigate

React provides several powerful hooks that help developers optimize performance and manage navigation efficiently. In this blog, we'll explore useMemo, useCallback, and useNavigate with simple examples.

1. useMemo Hook

What is useMemo?

useMemo is a React Hook used to memoize a calculated value. It prevents expensive calculations from running on every render and only recalculates when dependencies change.

Syntax

const memoizedValue = useMemo(() => {
return expensiveCalculation(data);
}, [data]);

Why use useMemo?

  • Improves performance
  • Avoids unnecessary recalculations
  • Useful for expensive operations

Example

import React, { useState, useMemo } from "react";

function App() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState("");

  const squaredValue = useMemo(() => {
    console.log("Calculating...");
    return count * count;
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>
      <h3>Square: {squaredValue}</h3>

      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>

      <input
        type="text"
        placeholder="Type here"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Output

  • Calculation runs only when count changes.
  • Typing in the input field does not trigger recalculation.

2. useCallback Hook

What is useCallback?

useCallback is a React Hook used to memoize a function. It prevents a function from being recreated on every render.

Syntax

const memoizedFunction = useCallback(() => {
// function logic
}, [dependencies]);

Why use useCallback?

  • Prevents unnecessary function recreation
  • Improves performance
  • Useful when passing functions to child components

Example

Parent Component

import React, { useState, useCallback } from "react";
import Child from "./Child";

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

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

  return (
    <div>
      <h2>Count: {count}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>

      <Child onClick={handleClick} />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Child Component

import React from "react";

const Child = React.memo(({ onClick }) => {
  console.log("Child Rendered");

  return (
    <button onClick={onClick}>
      Child Button
    </button>
  );
});

export default Child;
Enter fullscreen mode Exit fullscreen mode

Output

  • Child component re-renders only when the callback changes.
  • Since useCallback memoizes the function, unnecessary re-renders are avoided.

Difference Between useMemo and useCallback

useMemo useCallback
Memoizes a value Memoizes a function
Returns calculated value Returns function
Used for expensive calculations Used for function optimization
Improves rendering performance Prevents unnecessary re-renders

Example

const value = useMemo(() => count * 2, [count]);

const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);
Enter fullscreen mode Exit fullscreen mode

3. useNavigate Hook

What is useNavigate?

useNavigate is a hook provided by the React Router library. It allows users to navigate between pages programmatically.

Installation

npm install react-router-dom

Syntax

const navigate = useNavigate();

navigate("/about");
Enter fullscreen mode Exit fullscreen mode

Why use useNavigate?

  • Navigate to different pages
  • Redirect users after login
  • Navigate back and forward

Example
App.jsx

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Home.jsx

import { useNavigate } from "react-router-dom";

function Home() {
  const navigate = useNavigate();

  return (
    <div>
      <h1>Home Page</h1>

      <button
        onClick={() => navigate("/about")}
      >
        Go to About
      </button>
    </div>
  );
}

export default Home;
Enter fullscreen mode Exit fullscreen mode

About.jsx

function About() {
  return <h1>About Page</h1>;
}

export default About;
Enter fullscreen mode Exit fullscreen mode

Navigate Back

navigate(-1);

Moves to the previous page.

Navigate Forward

navigate(1);

Moves to the next page.

Replace Current History

navigate("/dashboard", { replace: true });

Prevents the user from returning to the previous page.

Conclusion

React hooks such as useMemo, useCallback, and useNavigate help developers build efficient and user-friendly applications.

useMemo → Memoizes values and avoids expensive recalculations.
useCallback → Memoizes functions and prevents unnecessary re-renders.
useNavigate → Enables programmatic navigation between routes.

Top comments (0)