react icon indicating copy to clipboard operation
react copied to clipboard

Bug: useReducer Object.is is not working

Open allroad88888888 opened this issue 3 years ago • 5 comments

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

allroad88888888 avatar Jul 22 '22 02:07 allroad88888888

I have also encountered, useState does not have this problem 😭

MinJieLiu avatar Jul 22 '22 10:07 MinJieLiu

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.

gaearon avatar Jul 22 '22 11:07 gaearon

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.

MinJieLiu avatar Jul 23 '22 10:07 MinJieLiu

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.

FenzaFenz avatar Jul 29 '22 06:07 FenzaFenz

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.

eps1lon avatar Jul 29 '22 06:07 eps1lon

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

mikirejf avatar Feb 23 '23 17:02 mikirejf