React useMap hook

React, Hooks, State · Nov 6, 2021

Creates a stateful Map object, and a set of functions to manipulate it.

  • Use the useState() hook and the Map constructor to create a new Map from the initialValue.
  • Use the useMemo() hook to create a set of non-mutating actions that manipulate the map state variable, using the state setter to create a new Map every time.
  • Return the map state variable and the created actions.
const useMap = initialValue => {
  const [map, setMap] = React.useState(new Map(initialValue));

  const actions = React.useMemo(
    () => ({
      set: (key, value) =>
        setMap(prevMap => {
          const nextMap = new Map(prevMap);
          nextMap.set(key, value);
          return nextMap;
        }),
      remove: (key, value) =>
        setMap(prevMap => {
          const nextMap = new Map(prevMap);
          nextMap.delete(key, value);
          return nextMap;
        }),
      clear: () => setMap(new Map()),
    }),
    [setMap]
  );

  return [map, actions];
};
const MyApp = () => {
  const [map, { set, remove, clear }] = useMap([['apples', 10]]);

  return (
    <div>
      <button onClick={() => set(Date.now(), new Date().toJSON())}>Add</button>
      <button onClick={() => clear()}>Reset</button>
      <button onClick={() => remove('apples')} disabled={!map.has('apples')}>
        Remove apples
      </button>
      <pre>
        {JSON.stringify(
          [...map.entries()].reduce(
            (acc, [key, value]) => ({ ...acc, [key]: value }),
            {}
          ),
          null,
          2
        )}
      </pre>
    </div>
  );
};

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

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 or Twitter.

More like this

  • React useSet hook

    Creates a stateful Set object, and a set of functions to manipulate it.

    React, Hooks · Nov 1, 2021

  • React useGetSet hook

    Creates a stateful value, returning a getter and a setter function.

    React, Hooks · Oct 27, 2021

  • React useLocalStorage hook

    Creates a stateful value that is persisted to localStorage, and a function to update it.

    React, Hooks · Sep 13, 2021