Flavien
Flavien

Reputation: 8127

Why is setState re-rendering the component when the value remains the same

The React documentation claims that if you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects.

However that doesn't seem to be the case in that example:

function Child() {
  useEffect(() => console.log("Re-render Child"));
  return (<div>Child</div>);
}

export default function App() {
  function Counter({ initialCount }) {

    const [state, setState] = useState({value: initialCount });

    useEffect(() => console.log("Re-render"));

    return (
      <>
        Count: {state.value}
        <br />
        <br />
        <button onClick={() => {
          state.value += 1;
          setState(state);
        }}>+1</button>
        <Child></Child>
      </>
    );
  }

  return (
    <div>
      <Counter initialCount={1} />
    </div>
  );
}

Clicking on the button only changes the inner property value, but the object remains the same, so why is React triggering a re-render (including a re-render of children and triggering the console.log effect)?

Here is a sandbox to test this: https://codesandbox.io/embed/react-hooks-counter-example-wrr2p

Upvotes: 3

Views: 372

Answers (2)

Mohamed Ramrami
Mohamed Ramrami

Reputation: 12691

The problem is that you are using an old React alpha version 16.7.0-alpha.0 (I don't think the bail out feature was implemented yet ). Just update to the latest version, and the problem is solved : updated sandbox

Upvotes: 1

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2796

use this code at first, you should import the usestate and you should specify where the value will be store in value:state+1

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

    setState({value:state+1});

Upvotes: 1

Related Questions