skip to Main Content

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()

2

Answers


  1. 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)
      }
    
    Login or Signup to reply.
  2. 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();
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search