Saturday, November 9, 2024

Mastering Performance Optimization Techniques with React Hooks

 Summary: More about hooks and optimization.

In this article, we will explore advanced performance optimization techniques using React Hooks. We'll delve into memoization, callback optimization, preventing unnecessary renders, state updates, and more. By mastering these techniques, developers can significantly enhance the performance of their React applications.

1. UseMemo:

The useMemo hook in React.js allows you to memorize the result of a function, meaning it caches the output and only re-evaluates the function when its dependencies change. This can improve performance by avoiding unnecessary computations on every render.

Syntax :

const memoizedValue = useMemo(() => {
// Expensive computation or function here
return result;
}, [dependencies]);

Example: Below is the code example:

JavaScript
// index.js 

import React, { useMemo } from 'react';
import ReactDOM from 'react-dom/client';
import './style.css'

function UseMemo() {
    const [count, setCount] = React.useState(0);
    // Simulate an expensive function to generate items
    const generateItems = useMemo(() => {
        const newItems = [];
        for (let i = 0; i < count * 5; i++) {
            newItems.push(`Item ${i + 1}`);
        }
        return newItems;
    }, [count]);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(prev => prev + 1)}>
                Increment
            </button>
            <ul>
                {generateItems.map((item) => (
                    <li key={item}>{item}</li>
                ))}
            </ul>
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <div id='main_container'>
        <div>
            <img src=
'https://media.geeksforgeeks.org/gfg-gg-logo.svg' alt='gfg_logo' />
        </div>
        <UseMemo />
    </div>
);

Output:

1711080929553
useMemo project output

2. useCallback

React's useCallback hook is another tool for performance optimization. Unlike useMemo which caches the result of a function, useCallback focuses on memorizing the function itself. UseCallback allows you to memorize a function, meaning it returns the same function reference as long as its dependencies haven't changed. Here's how it helps.

Syntax:

const memoizedFunction = useCallback(() => {
// Function body
}, [dependencies]);

Example: Below is the code example:

JavaScript
// index.js 

import React, { useState, useCallback } from 'react';

function ParentComponent(props) {
    const [data, setData] = useState([]);

    const handleClick = useCallback(() => {
        // Perform action using data
    }, [data]);

    return (
        <div>
            <ChildComponent handleClick={handleClick} />
            <button onClick={() => setData([...data, Math.random()])}>
                Add Item
            </button>
            {
                data.map((val) => (
                    <li key={val}>{val}</li>
                ))
            }
        </div>
    );
}

function ChildComponent(props) {
    return <button onClick={props.handleClick}>Click me</button>;
}

const root = ReactDOM.createRoot(
    document.getElementById('root')
);
root.render(
    <div id='main_container'>
        <div>
            <img src=
'https://media.geeksforgeeks.org/gfg-gg-logo.svg' alt='gfg_logo' />
        </div>
        <ParentComponent />
    </div>
);

Output:

1711084427217
useCallback Project Output

3. React.memo

In React, React.memo is a Higher-Order Component (HOC) that helps improve performance by preventing unnecessary re-renders of functional components. It use Memoization technique to optimize the performance of React components by caching the result of the component's rendering and reusing it if the component's props remain unchanged. It leads to lower memory usage due to less re-render. Here's a breakdown of how it works:

Syntax:

const MemoizedComponent = React.memo(FunctionalComponent);

Example: Below is the code example:

JavaScript
// index.js

import React from 'react'

const ListItem = React.memo(({ value }) => {
    console.log(`Rendering item with value: ${value}`);

    return (
        <div>
            <p>Value: {value}</p>
        </div>
    );
});

const List = ({ itemCount = 10 }) => {
    const items =
        Array.from({ length: itemCount }, (_, index) => ({
            id: index,
            value: Math.random() * 1000
            // Generate a random number
        }));

    return (
        <div>
            <h2>List</h2>
            {items.map(item => (
                <ListItem key={item.id} value={item.value} />
            ))}
        </div>
    );
};


const root = ReactDOM.createRoot(
    document.getElementById('root')
);
root.render(
    <div id='main_container'>
        <div>
            <img src=
'https://media.geeksforgeeks.org/gfg-gg-logo.svg' alt='gfg_logo' />
        </div>
        <List />
    </div>
);

Output:

1711086323246
React.memo Browser Output

4. UseEffect:

UseEffect is a powerful hook in React for performing side effects like data fetching, subscriptions, or setting up timers. By specifying dependencies, you can control when the effect runs. If any of the dependencies change between renders, the effect function will be called again and if dependencies array is empty it runs only once. However, if used incorrectly, it can lead to unnecessary re-renders, impacting your application's performance

Syntax

useEffect(() => {
// Side effect code here
return () => {
// Cleanup code here (optional)
};
}, [dependencies]);

Example: Below is the code example:

JavaScript
// 

function MyComponent(props) {
    const [data, setData] = React.useState(null);

    // Fetches data only once (empty dependency array)
    useEffect(() => {
        fetch('https://api.example.com/data')
            .then((response) => response.json())
            .then((data) => setData(data));
    }, []);

    return (
        <div>
            {data ? (
                <p>Fetched Data: {data.message}</p>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
}

5. React Virtualization

Rendering large lists in React can lead to performance issues due to large number of DOM elements being created and managed. React Virtualization is a technique used to optimize the rendering of large lists by only rendering the items that are currently visible on the screen. This significantly reduces the memory footprint and improves the performance of your application.

It is not a part of core React, So you have to install it separately by using the following command.

npm install react-virtualized

Example: Below is the code example:

JavaScript
// index.js 

import React,
{
    useState,
    useEffect
} from 'react';
import { List as VirtualList } from 'react-virtualized';
const LARGE_LIST_SIZE = 1000; // Number of items in the list

function VirtualListComp() {
    const [items, setItems] = useState([]);

    // Simulate data generation (replace with your actual data fetching logic)
    useEffect(() => {
        const newItems = [];
        for (let i = 1; i <= LARGE_LIST_SIZE; i++) {
            newItems.push({ id: i, content: `Item ${i}` });
        }
        setItems(newItems);
    }, []);

    const rowRenderer = ({ index, style }) => {
        const item = items[index];
        return (
            <div key={item.id} style={style}>
                {item.content}
            </div>
        );
    };

    return (
        <div className="App">
            <h1>Large List Example</h1>
            <VirtualList
                width={400}
                height={400}
                rowCount={items.length}
                rowHeight={40} // Height of each item
                rowRenderer={rowRenderer}
            />
        </div>
    );
}

const root = ReactDOM.createRoot(
    document.getElementById('root')
);
root.render(
    <div id='main_container'>
        <div>
            <img src=
'https://media.geeksforgeeks.org/gfg-gg-logo.svg' alt='gfg_logo' />
        </div>
        <VirtualListComp />
    </div>
);

Output:

d3068834-5203-4a9c-9f2a-81136eb07a57-ezgifcom-video-to-gif-converter
React Virtualization Output

6. useRef:

UseRef() is a hook provided by React that creates a mutable reference object which persists across renders of a functional component. It returns a single mutable value object ({current}) that can be updated without causing re-renders. useRef() is commonly used to access or store values that persist between renders without triggering component re-renders.

Example: Below is the code example:

JavaScript
// index.js 

import React, { useRef } from 'react';

const Counter = () => {
    const countRef = useRef(0);
    // Initialize countRef with initial value of 0

    const increment = () => {
        countRef.current += 1;
        // Increment the current value of countRef
        updateCounter();
        // Call updateCounter to update the displayed count
    };

    const reset = () => {
        countRef.current = 0;
        // Reset the current value of countRef to 0
        updateCounter();
        // Call updateCounter to update the displayed count
    };

    const updateCounter = () => {
        // Update the counter displayed in the UI
        document.getElementById('counter').innerText = countRef.current;
    };

    return (
        <div>
            <h2>Counter</h2>
            <p>Count: <span id="counter">
                {countRef.current}
            </span></p>
            <button onClick={increment}>Increment</button>
            <button onClick={reset}>Reset</button>
        </div>
    );
};

const root = ReactDOM.createRoot(
    document.getElementById('root')
);
root.render(
    <div id='main_container'>
        <div>
            <img src=
'https://media.geeksforgeeks.org/gfg-gg-logo.svg' alt='gfg_logo' />
        </div>
        <Counter />
    </div>
);

Output:

9ab80655-1c2f-4122-bc06-19e1112cbafe-ezgifcom-video-to-gif-converter
UseRef Browser Output

Want to be a Software Developer or a Working Professional looking to enhance your Software Development Skills? Then, master the concepts of Full-Stack Development. Our Full Stack Development - React and Node.js Course will help you achieve this quickly. Learn everything from Front-End to Back-End Development with hands-on Projects and real-world examples. This course enables you to build scalable, efficient, dynamic web applications that stand out. Ready to become an expert in Full-Stack? Enroll Now and Start Creating the Future!


Similar Reads

When is it best to use custom hooks instead of built-in React hooks?
Custom hooks in React are useful when you want to extract and reuse stateful logic across multiple components. While built-in React hooks like useState, useEffect, and useContext cover many common scenarios, there are cases where creating custom hooks can enhance code organization, readability, and reusability. When to Choose for Custom Hooks in Re
2 min read
Performance Hooks in React
While developing React Applications, optimizing performance is one of the most important things for delivering a seamless user experience. One common way to boost performance is to minimize unnecessary re-renders by skipping repetitive calculations. React provides two powerful hooks, useMemo and useCallback, which helps you to achieve optimization
3 min read
Mastering React Routing: Learn Navigation and Routing in React Apps
In this article, we will learn how to implement Routing in React in an efficient way by implementing various aspects of routing such as dynamic routing, programmatically routing, and other concepts. Table of ContentWhat is Navigation in React?Routing with no page found(error 404) error handlingProgrammatic Navigation in ReactDynamic Routing with Re
6 min read
Optimizing Performance with useMemo and useCallback Hooks
In React applications, optimizing performance is crucial for ensuring smooth user experiences, especially in components with complex computations or frequent re-renders. Two hooks provided by React, useMemo, and useCallback, offer efficient ways to achieve performance improvements by memoizing values and callback functions, respectively. Table of C
4 min read
Why to use React Hooks Instead of Classes in React JS ?
The introduction of React Hooks has changed the way we are managing states and lifecycle features. They offer more easy and functional way as compared to class based components. In this article, we will learn why to use React Hooks Instead of Classes in ReactJS, but lets first discuss about both React hooks and class based components. Table of Cont
4 min read
What are React Hooks, and why were they added to React?
React Hooks are a way to add functionality to functional components in React. Before Hooks, functional components were more limited compared to class components in terms of what they could do. With Hooks, users can now use state, lifecycle methods, and other React features in functional components, making them more powerful and flexible. Hooks Addr
2 min read
What are the React Router hooks in React v5?
React Router hooks perform client-side single-page routing that provides a functional and streamlined approach to managing navigation in React applications. It provides a way to directly access the state of the router from functional components, this simplifies tasks like retrieving information about the desired URL and navigating through web pages
5 min read
Explain the new feature of React hooks introduced in React v16.8
React v16.8 is no less than a miracle for all the React developers because this version of React introduced hooks to all of us. Before its release, the developer community was tired of using class components but they still had to use them because the functional component does not provide many features that the class component provides. But after ho
7 min read
Next.js Bundle Optimization to improve Performance
In this article, We will learn various ways to improve the performance of the NextJS bundle which results in increasing the performance of NextJS applications in Google PageSpeed Insights or Lighthouse. As per the documentation, NextJS is a React framework that gives you the building blocks to create web applications. Building Blocks means various
6 min read
How to set an object key inside a state object in React Hooks?
We can update a React hooks state object that has a nested object containing objects with index keys with the following approach, Before doing so, consider the following example: Example: Following is the default state object: const [data, setData] = useState({ name:'', contact:'', address:{ 0:{}, 1:{}, } }) Following is the desired output after up
2 min read
How to use componentWillMount() in React Hooks?
The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle. You cannot use any of the existing React lifecycle methods like ComponentDidMount, ComponentWillUnmount, etc. in a ho
2 min read
React Suite Notification Props & Hooks
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Notification Component allows the user to display a notification message globally. The notification is also used with a toaster in react-based applications. <Notification> Props: closable: It is a boolean
4 min read
Things You Should Know About React Hooks
React...We all know the importance of this library in the tech industry. Most of the applications are switching to React because of its advantages and features. There are many features of React. React hooks is one of them. React hooks was first released in October 2018. In React a lot of developers use the lifecycle method which is nothing, but jus
4 min read
How to build a Tic-Tac-Toe Game using React Hooks ?
To build a Tic-Tac-Toe using react Hooks include the interactive components that represent the board, the signs, and at last the winner of the game. Preview of final output: Let us have a look at how the final application will look like. Prerequisite of Tic-Tac-Toe Game:Introduction to ReactFunctional Components in ReactReact HooksNPM & Node.js
8 min read
How to generate random colors by using React hooks ?
In web development, colors play a vital role in creating visually appealing and engaging user interfaces. In React we may need to generate random colors dynamically. In this article, we will explore how to achieve this using React hooks, a powerful feature introduced in ReactJs. Pre-requisite:NPM & Node.jsReact.jsReact HooksApproach:To generate
2 min read
React JS Hooks Reference
React hooks are functions that enable functional components to use state and lifecycle features that were previously only available in class components. Example: Below is the basic representation of the React JS Hooks useState. C/C++ Code import React, { useState } from 'react'; import './App.css' const App = () => { const [num, setNum] = useSta
2 min read
State Management in React – Hooks, Context API and Redux
While developing a React Application, it is very important to manage the state efficiently for building fully functional applications. As React is growing there are multiple approaches introduced that can help to manage state efficiently depending upon the type of application we are building. We will discuss the following state management technique
6 min read
New Hooks in React 18
React's state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state and lifecycle management in functional components,
6 min read
Which versions of React include Hooks?
React Hooks were introduced in React version 16.8. They were a significant addition to the React library and provided a new way to work with stateful logic and side effects in functional components. Before the introduction of Hooks, stateful logic was primarily managed in class components using the lifecycle methods. React Hooks, including useState
1 min read
Rules for using hooks in React
Using hooks in React follows several rules and guidelines to ensure proper functionality and maintain code quality: Hooks should only be used at the top level of functional components: Hooks should not be called conditionally or within nested functions, loops, or other JavaScript constructs. They should always be called at the top level of a functi
2 min read
What are the benefits of using hooks in React-Redux?
Have you ever wondered how users create amazing websites and apps? Well, in the world of programming, they have some cool tools, and today we're going to explore one of them called "Hooks" in the superhero team of React-Redux. Prerequisites:ReactReact-ReduxReact HooksJavaScriptWhat are Hooks?Hooks are functions and essential mechanisms that optimiz
2 min read
How are React Hooks different from class components in ReactJS?
React Hooks are helpful tools that make building websites and apps with React easier. They simplify how users handle things like data and app behavior, making the code cleaner and easier to understand. Class components in React are like the old-school way of building parts of your website or app. They use JavaScript classes to structure components,
2 min read
What is useMemo in React Hooks, and why is it useful?
useMemo is a React Hook that is used to optimize performance by memoizing the result of a function or computation. In simpler terms, it remembers the value that a function returns, so that the function doesn't have to be recalculated every time the component re-renders. Why useMemo is useful ?Performance Optimization:When a component re-renders, al
2 min read
What's the useCallback hook used for in React Hooks?
The useCallback hook in React Hooks is used to optimize the performance of your React applications. It's helpful when you have a function that you want to pass down to child components, but you don't want those child components to re-render unnecessarily every time the parent component re-renders. Benefits of useCallback Hook in React Hooks:Perform
2 min read
Can you explain what the useState hook does in React Hooks?
The useState hook is a feature in React Hooks that allows you to add state to functional components. It creates state variables and manages their values within a functional component. Why is useState important?Before introducing hooks in React, state management was only possible in class components. However, with the useState hook, users can now in
2 min read
What's the role of the useContext hook in React Hooks?
The useContext hook in React Hooks allows you to consume values from the React context without needing to explicitly pass props through every level of your component tree. Role of useContext hook in React Hooks:Accessing Context Values:With useContext, you can access values stored in a React context from any component within the same context provid
2 min read
What's the useDebugValue hook for in React Hooks?
The useDebugValue hook in React is a user tool that allows you to display custom labels for custom hooks in React DevTools. It's primarily used for debugging and improving the user experience when working with custom hooks. Understanding the useDebugValue Hook in React:Debugging Custom Hooks: When you create custom hooks in React, it can sometimes
2 min read
Built-in React Hooks
In React, built-in Hooks are like tools that empower your components with various functionalities. They give you the flexibility to use different features without having to create class components. You can either utilize the hooks provided by React or mix and match them to create custom hooks tailored to your needs. Here's a list of all the pre-bui
5 min read
Mimicking Lifecycle Methods with Hooks in React
React Hooks provides a powerful way to manage state and lifecycle events in functional components. However, if you're transitioning from class components to functional components, you might miss the familiar lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. Fortunately, you can achieve similar functionality usi
5 min read
Effect Hooks in React
Effect Hooks in React allow components to interact with and stay synchronized with external systems, such as handling network requests, manipulating the browser's DOM, managing animations, integrating with widgets from other UI libraries, and working with non-React code. Essentially, effects help components communicate and coordinate with the world
5 min read

No comments:

Post a Comment

React Profiler: A Step by step guide to measuring app performance

  As react applications are becoming more and more complex, measuring application performance becomes a necessary task for developers. React...