Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useState() do double render

I'm using useState() in function component and first render is calling twice. Is it correct or mistake? If it is correct why does it render twice? setCount renders the component twice too.

function Example() {
  const [count, setCount] = useState(0);
  console.log("render");

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('uu5'));

Thanks

like image 827
Ondřej Čapek Avatar asked Feb 28 '19 14:02

Ondřej Čapek


People also ask

Does useState cause rendering?

You may call setState() immediately in componentDidMount() . It will trigger an extra rendering, but it will happen before the browser updates the screen.

Does useState run on every render?

useState takes the initial value of the state variable as an argument. The initial value will be assigned only on the initial render (if it's a function, it will be executed only on the initial render).

Can you use useState multiple times?

You can use useState multiple times. In fact it's even recommended in the React docs. we recommend to split state into multiple state variables based on which values tend to change together.

What does useState function do?

The useState() is a Hook that allows you to have state variables in functional components . so basically useState is the ability to encapsulate local state in a functional component.


1 Answers

According to react docs, it's an intentional feature to help you to detect unexpected side effects if you're using StrictMode

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

Note: This only applies to development mode. Lifecycles will not be double-invoked in production mode.

https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

like image 192
Jorge Arimitsu Avatar answered Sep 20 '22 20:09

Jorge Arimitsu