Files
30-seconds-of-code/react/snippets/use-update.md
Angelos Chalaris 462322f885 Prepare for merge
2023-05-01 22:56:37 +03:00

682 B

title, type, tags, author, cover, dateModified
title type tags author cover dateModified
React useUpdate hook snippet
components
reducer
chalarangelo lavender-shelf 2021-09-24T05:00:00-04:00

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