It appears that when reactStrictMode is set to true in next.config.js, components are rendered twice when using react hooks.
pages/index.js
const Index = () => {
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>
);
};
next.config.js
module.exports = {
reactStrictMode: true
}
On load, you'll see it render twice. When you click, it'll render twice for each click.
Should render once for each state change
This is how StrictMode is designed to work (the double renders are a React feature)! The docs for StrictMode explain the reasoning.
tl;dr:
Strict mode can鈥檛 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 methods [...]
This behavior ensures your renders do not produce side-effects.
Most helpful comment
This is how
StrictModeis designed to work (the double renders are a React feature)! The docs for StrictMode explain the reasoning.tl;dr:
This behavior ensures your renders do not produce side-effects.