“ useState”仅在对象中的值更改时更新组件



useState always triggers an update even when the data's values haven't changed.

Here's a working demo of the problem: demo


I'm using the useState hook to update an object and I'm trying to get it to only update when the values in that object change. Because React uses the Object.is comparison algorithm to determine when it should update; objects with equivalent values still cause the component to re-render because they're different objects.

Ex. This component will always re-render even though the value of the payload stays as { foo: 'bar' }

const UseStateWithNewObject = () => {
  const [payload, setPayload] = useState({});
    () => {
      setInterval(() => {
        setPayload({ foo: 'bar' });
      }, 500);

  renderCountNewObject += 1;
  return <h3>A new object, even with the same values, will always cause a render: {renderCountNewObject}</h3>;

Is there away that I can implement something like shouldComponentUpdate with hooks to tell react to only re-render my component when the data changes?

  • sest 回复


    const Component = React.memo(props => (
      <div>Memoized component</div>