react
react copied to clipboard
Bug: useReducer Object.is is not working
React version:18.0.2
react render executed twice
useReducer returns the state itself, but still executes one more time
Steps To Reproduce
const DemoUseState = () => {
const [state, setState] = useState({ count: 1 });
useEffect(() => {
setState(state);
}, []);
console.log("useState only render once");
return <div>DemoUseState only render once</div>;
};
const reducer = (state, action) => {
return state;
};
const DemoUseReducer = () => {
const [, dispatch] = useReducer(reducer, { count: 1 });
useEffect(() => {
dispatch({ type: "decrement" });
}, []);
console.log("useReducer render twice");
return <div>DemoUseReducer render twice</div>;
};
export default function App() {
return (
<div className="App">
<DemoUseReducer />
<DemoUseState />
</div>
);
}
example:https://codesandbox.io/s/cool-flower-5yx1pg?file=/src/App.js
I have also encountered, useState does not have this problem 😭
What are the exact reproduction steps? It’s not obvious what you’re doing, what you’re seeing, and what you’re expecting to see. Please be precise.
useReducer dispatch does not change the data will have additional render.
And useState will not have this time render
In react 17 there will be no such problem.
https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update
Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree.
It sounds like the expected behavior described by @FenzaFenz but without a clear reproduction (minimal code that reproduces the issue ideally with codesandbox or cloneable repository) it's hard to tell.
Please check the following example: codesandbox v18
The state is always the same and preferentially stable (number 15). However, the component rerenders on every button click. That doesn't reflect the behavior described in the docs: https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-dispatch
React v17 version works as expected: codesandbox v17