Rajesh Kumar
Rajesh Kumar

Reputation: 196

Change of state is not getting affected in another unmount useEffect in react hooks

New to react Hooks.

// create as state using useState
  const [clearSelected,setClearSelected] = useState(true);

//clearSelected is changed to false
 setClearSelected(false);

Since there is no callback function in the hooks i wait till the clearSelected becomes false then i move to another page

 useEffect(()=>{
//clear selected is set to false and then redirection to another page is done

    if(clearSelected === false){

      history.push('/nextPage');
    }
  },[clearSelected]);
//clears the redux state on unmount
useEffect(()=>{ 
    return (()=>{
       //should not go inside when clearSelected is false 
      if(clearSelected){
       //clear the redux state
        actions.items([], false);
      }
    })
  },[]);

The redux state is getting cleared even though redirection is done after clearSelected became false.

I printed the clearSelected inside the above unmount hook.It is true.

May i know why its not working. Thanks.

Upvotes: 3

Views: 664

Answers (2)

jayarjo
jayarjo

Reputation: 16726

You basically create a closure in the second useEffect, which effectively locks on the initial value for the state (true):

useEffect(()=>{ 
    return (()=>{ // closure that holds initial value of the `clearSelected`
      // ...
    })
  },[]);

If you want to retain access to the current state in closures, consider storing a reference to it with useRef.

So, something like this:

const [clearSelected, setClearSelected] = useState(true);
const clearSelectedRef = useRef(clearSelected);

useEffect(() => {
    clearSelectedRef.current = clearSelected;
    if (clearSelected === false) {
        history.push('/nextPage');
    }
}, [clearSelected]);

useEffect(() => {
    return (() => {
        //should not go inside when clearSelected is false 
        if (clearSelectedRef.current) {
            //clear the redux state
            actions.items([], false);
        }
    })
}, []);

Upvotes: 1

J. Hesters
J. Hesters

Reputation: 14786

The reason why clearSelected is false is because of closure.

Your function

()=>{
  //should not go inside when clearSelected is false 
  if(clearSelected){
    //clear the redux state
    actions.items([], false);
  }
}

gets the clearSelected state when it is mounted. You can read more about Closures here.

You will need to use useRef and it's current value to get your code working.

Furthermore, here is a guide on useEffect by Dan Abromov. It will help you understand useEffect.

Upvotes: 0

Related Questions