0

I am new to react and react hooks. I am creating a custom react hook. Why is useState not working as expected.

import { useEffect, useState } from 'react'

export const useMyHook = () => {
  const [myVal, setVal] = useState(0) //myVal is 0
  
  useEffect(() => {
    initialize()
  },[])
  
  const initialize = () => {
    setVal(100)
    console.log(myVal) // displays 0, not 100 as I expect
  }

  return myVal
}


// In my component I call it as follows
import { useMyHook } from 'useMyHook'
...
const myHook = useMyHook()

Bill Haack
  • 375
  • 1
  • 4
  • 10
  • It's working how it's supposed to, the value is only updated on the next render. See [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Samathingamajig Jul 26 '23 at 02:57

2 Answers2

0

I think you misunderstand the useState here.

First, when the component using the useMyHook is mounted, the useEffect runs as part of the initial render, and it calls the initialize function due to the [] dependency.

Then, inside the initialize function, you call setVal(100) to update the value of myVal. However, the update is asynchronous, meaning that the new value won't be available immediately. At this point, the myVal state variable still holds its old value of 0 because the state update is not yet completed

If you want to log the latest myVal value you can use useEffect like this

useEffect(() => {
    initialize()
  },[])
  
  useEffect(() => {
    console.log(myVal) // Will display the updated value of myVal whenever it changes
  }, [myVal])

  const initialize = () => {
    setVal(100)
  }
Tony
  • 1,106
  • 1
  • 10
  • 17
0

To see the updated value of myVal, you can use the useEffect hook with a dependency on myVal. When the value of myVal changes, the effect will run, and you can log the updated value.

import { useEffect, useState } from 'react';

export const useMyHook = () => {
  const [myVal, setVal] = useState(0);

  useEffect(() => {
    initialize();
  }, []);

  const initialize = () => {
    setVal(100);
  };

  useEffect(() => {
    console.log(myVal); // This will log the updated value of myVal whenever it changes
  }, [myVal]);

  return myVal;
};

import { useMyHook } from 'useMyHook';

const MyComponent = () => {
  const myHook = useMyHook();
};
Hoang Long
  • 446
  • 4
  • 5