skip to Main Content

How can we stop re-rendering if the value of the useState object remains the same?

When I click on the button, the dataChange function is triggered. I am updating the useState object value; the value is the same, but the component is re-rendering on every click of the button.

const App = () => {
  console.log('APP re-render :>> ', Math.random());
  const [data, setData] = useState({ value:1 });

  const dataChange = () => {
    setData({value:1});
  }
  return (
    <div>
      <button onClick={dataChange}>Click</button>
      <p>{data.value}</p>      
    </div>
  )
}

4

Answers


  1. You may be using the same value, but they are not the same. i.e.

    {value: 1} != {value: 1} // true
    

    If you want to use the same object, define a constant outside your component, and use that in place of {value: 1}:

    const myData = {value: 1};
    myData == myData; // true
    
    Login or Signup to reply.
  2. you can use use useMemo hook to avoid the rerendering

    import React, { useState, useMemo } from 'react';
    
    const App = () => {
      console.log('APP re-render :>> ', Math.random());
      const [data, setData] = useState({ value: 1 });
    
      const dataChange = useMemo(() => () => {
        setData(prevData => {
          if (prevData.value !== 1) {
            return { value: 1 };
          }
          return prevData;
        });
      }, [data]);
    
      return (
        <div>
          <button onClick={dataChange}>Click</button>
          <p>{data.value}</p>      
        </div>
      );
    };
    
    export default App;
    
    
    Login or Signup to reply.
  3. useState is not a database, you need to add logic to compare the current state and the new state if they’re the same just return the current state else update the state . You can use useMemo hook like this ;

    const dataChange = useMemo(() => () => {
        setData(prevData => {
          if (prevData.value !== 1) {
            return { value: 1 };
          }
          return prevData;
        });
      }, [data]);
    
    Login or Signup to reply.
  4. To prevent a re-render when the value of the useState object remains the same, you need to check if the new state is actually different from the current state before updating it. If the state hasn’t changed, you can avoid calling the state updater function.

    One way to do this is to use a functional update with setData to ensure that the new state is compared with the current state. Here’s how you can modify your dataChange function to perform this check:

    import React, { useState } from 'react';
    
    const App = () => {
      console.log('APP re-render :>> ', Math.random());
      const [data, setData] = useState({ value: 1 });
    
      const dataChange = () => {
        setData(prevData => {
          // Only update state if the new value is different
          if (prevData.value !== 1) {
            return { value: 1 };
          }
          // Return the same state to avoid re-rendering
          return prevData;
        });
      };
    
      return (
        <div>
          <button onClick={dataChange}>Click</button>
          <p>{data.value}</p>
        </div>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search