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
You may call setState() immediately in componentDidMount() . It will trigger an extra rendering, but it will happen before the browser updates the screen.
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With