30秒学会 React 片段 · 2022年8月22日

30秒学会 React 片段 – React useUpdate hook

Forces the component to re-render when called.

  • Use the useReducer() hook that creates a new object every time it’s updated and return its dispatch.

代码实现

const useUpdate = () => {
  const [, update] = React.useReducer(() => ({}));
  return update;
};

使用样例

const MyApp = () => {
  const update = useUpdate();

  return (
    <>
      <div>Time: {Date.now()}</div>
      <button onClick={update}>Update</button>
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <MyApp />
);

翻译自:https://www.30secondsofcode.org/react/s/use-update