3

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

4
  • You are using this in the wrong way. Use useEffect(() => console.log("Re-render"), []); Commented Aug 20, 2019 at 11:13
  • 1
    > Note that React may still need to render that specific component again before bailing out. Literally the next line in docs. Commented Aug 20, 2019 at 11:17
  • @VaibhavVishal Sure, but it also renders children again as well. I've tested it. Commented Aug 20, 2019 at 11:18
  • 1
    @PraveenKumarPurushothaman No, I want to trigger the effect on each render, so I shouldn't be providing a [] argument. Commented Aug 20, 2019 at 11:23

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good catch! I knew I was missing something obvious.
1

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});

1 Comment

That's not answering the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.