How to run multiple React useStates at the same time?

Viewed 73

How to make the result of both functions apply without changing the code inside copyAll? Real life example: one function changes the state by clicking on a button, another by document.addEventListener.

import { useState, useCallback } from "react";

export default function App() {
  const [xxx, setXXX] = useState({ "1": null, "2": null });

  const one = useCallback(
    (val) => {
      setXXX(() => ({ ...xxx, "1": val }));
    },
    [setXXX, xxx]
  );

  const two = useCallback(
    (val) => {
      setXXX(() => ({ ...xxx, "2": val }));
    },
    [setXXX, xxx]
  );

  const copyAll = () => {
    one(1);
    two(2);
  };

  console.log("xxx", xxx);

  return <button onClick={copyAll}>Copy All</button>;
}
1 Answers

Use funcional setState:

import { useState, useCallback } from "react";

export default function App() {
  const [xxx, setXXX] = useState({ "1": null, "2": null });

  const one = useCallback(
    (val) => {
      // add xxx as param here
      setXXX((xxx) => ({ ...xxx, "1": val }));
    },
    [setXXX]
  );

  const two = useCallback(
    (val) => {
      // add xxx as param here
      setXXX((xxx) => ({ ...xxx, "2": val }));
    },
    [setXXX]
  );

  const copyAll = () => {
    one(1);
    two(2);
  };

  console.log("xxx", xxx);

  return <button onClick={copyAll}>Copy All</button>;
}
Related