“ 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({});
  useEffect(
    () => {
      setInterval(() => {
        setPayload({ foo: 'bar' });
      }, 500);
    },
    [setPayload]
  );

  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>
    ));