score:4

Accepted answer

react state updates are asynchronous, i.e. queued up for the next render, so the log is displaying the state value from the current render cycle. you can use an effect to log the value when it updates. this way you log the same state.value as is being rendered, in the same render cycle.

export default function app() {
  const [state, setstate] = usestate({
    value: ""
  });

  useeffect(() => {
    console.log(state.value);
  }, [state.value]);

  let handlechange = input => {
    setstate(prevvalue => {
      return { value: input };
    });
  };

  return (
    <div classname="app">
      <h1>{state.value}</h1>

      <child handlechange={handlechange} value={state.value} />
    </div>
  );
}

score:0

maybe it is helpful for others i found this way...

i want all updated projects in my state as soon as i added them so that i use use effect hook like this.

useeffect(() => {
    [temp_variable] = projects //projects get from useselector
    let newformvalues = {...data}; //data from usestate
    newformvalues.projects = pro; //update my data object
    setdata(newformvalues); //set data using usestate
},[projects]) 

score:1

two solution for you: - use input value in the handlechange function

let handlechange = input => {
   setstate(prevvalue => {
     return { value: input };
   });
   console.log(state.value);
 };
  • use a useeffect on the state

    useeffect(()=>{ console.log(state.value) },[state])


Related Query

More Query from same tag