Files
30-seconds-of-code/snippets/useUpdate.md
2022-06-08 12:56:09 +03:00

684 B

title, tags, expertise, author, cover, firstSeen
title tags expertise author cover firstSeen
React useUpdate hook components,reducer beginner chalarangelo blog_images/lavender-shelf.jpg 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.render(<MyApp />, document.getElementById('root'));