React useUpdate hook

React, Components, Reducer · Sep 24, 2021

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

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • Tabs

    Renders a tabbed menu and view component.

    React, Components · Oct 13, 2021

  • Modal dialog

    Renders a Modal component, controllable through events.

    React, Components · Oct 13, 2021

  • Stateful checkbox with multiple selection

    Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.

    React, Components · Oct 13, 2021