skip to Main Content

I’m having trouble with React Native showing wrong value for me. I wan’t to show the value after an useState update. My goal is to pass the value to the parent component but right now it passes the opposite value (true when switch is off). What do I have to do to console.log the right value after a useState update?

Watch image for example here

4

Answers


  1. The useState hook is somewhat asynchronous (although you cannot wait for it).

    Try using a useEffect:

    useEffect(() => {
       console.log(isEnabled)
    }, [isEnabled]) // Array of dependencies: when any of these value changes, the function in the useEffect will re-run
    

    More information here:

    Login or Signup to reply.
  2. State updates in React are asynchronous, meaning that React does not wait for the state to be updated before executing the next line of code. In your case, the state update setIsEnabled(...) is not finished before console.log(isEnabled) is run, and therefore it returns the old value.

    Just put the console.log(isEnabled) outside the function for it to print the update correctly. The component SetupSwitch is re-rendered when the state isEnabled is updated, which means it prints the console.log of the updated variable again.

    ...
    console.log(isEnabled);
    const Change = () => {
    ...
    Login or Signup to reply.
  3. You will have to implement useEffect to view the changes.
    useState is an asynchronous function it will go to the callback queue, meanwhile, the value will be consumed, so you need to trigger the action whenever the count changes. (for this example)

    const [count, setCount] = useState(0);
    
    useEffect(() => console.log(count), [count]);
    
    setCurrPos(preevCount => prevCount + 1);
    
    
    Login or Signup to reply.
  4. The Change function will always "see" the state value that existed at the time of running the function. This is not because of asynchronicity per se (state updates are actually sync) but because of how closures work. It does feel like it is async though.

    The state value will properly update in the background, but it won’t be available in the "already-running" function. You can find more info here.

    The way I see your handler implemented though:

        const handleChange = () => {
          setIsEnabled(!isEnabled) // you do not need updater function, you can directly reference the state
          triggerParentMethod(!isEnabled); // then you can also directly call the parent function here
        }
    

    I recommend this as this way you will notify the parent immediately on user click instead of waiting for the state to be set and then notifying the parent in the next render cycle (in the effect), which should be unnecessary.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search