1

The React state is not updating immediately. I want to update the state immediately on the press of Play button.

import * as React from "react";
import { Button } from "react-native";
export default function Play() {
  const [player, setPlayer] = React.useState(1);
  function nextPlayer() {
    setPlayer(2);
    updateValue();
  }
  function updateValue() {
    if (player == 1) {
      console.log("player 1");
    } else if (player == 2) {
      console.log("player 2");
    }
  }
  return <Button title="play" onPress={nextPlayer} />;
}
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
  • Can you clarify what you are supposed to do? – Jignesh Mayani Feb 15 '21 at 14:12
  • You can format your code using either `\`\`\`multiline-code-here\`\`\`` or a single item by `\`putting them inside ticks\``. It really helps. – OArnarsson Feb 15 '21 at 14:16
  • 1
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Luís Silva Feb 15 '21 at 14:33

1 Answers1

2

The function updateValue is created in the Closure that contains the "old value" of your state. If you want it to run with the new values, use an useEffect hook or pass the current value as an argument.

const [value, setValue] = useState();

useEffect(() => {
  // receives the latest value and is called on every change (also the first one!)
}, [value])
Jonathan
  • 3,614
  • 3
  • 21
  • 30