DEV Community

Cover image for React cant reach current state
mertyjsx
mertyjsx

Posted on

React cant reach current state

https://codesandbox.io/s/the-appropriate-use-of-usecallback-forked-o55n6?file=/src/Example.js:248-400
hello i have a problem
I created a useState called [users, setusers]
and in useeffect, I have assigned a delete function for each user.
this delete function needs to reach users state

But the problem starts here. When I want to reach users through the delete function,
I get the initial state of the state, (the state at the time I created the first user object)

Top comments (3)

Collapse
 
justincy profile image
Justin

You can get the latest value by passing a function to setUsers and it will be passed the current value as a parameter. See reactjs.org/docs/hooks-reference.h...

Collapse
 
mertyjsx profile image
mertyjsx

can you look at this,codesandbox.io/s/the-appropriate-u...
what is the reason of this

  1. row console.log(users) getting empty array
Collapse
 
justincy profile image
Justin • Edited

Because of a stale closure, following the rules of Javascript closures and scope. dmitripavlutin.com/react-hooks-sta...

Here's what you want:

  const delet = (id) => {
    setUsers((currentUsers) => {
      return currentUsers.filter((i) => i.id !== id);
    });
  };
Enter fullscreen mode Exit fullscreen mode

codesandbox.io/s/the-appropriate-u...