When I click NewTab
button, newtab
state will change and I want to call useEffect
when newTab
state change, so it will goBack()
, and will call return statement as well, but somehow return statement executing twice, with both old value and new value (false , true respectively).
Here is my problem statement.
const App = () => {
const [newTab, setNewTab] = useState(false);
useEffect(() => {
if (newTab) {
navigation.goBack();
}
return () => { // call twice first get false, and second time get true
if (newTab == false) {
//clear the redux data
}
}
}, [newTab]);
return (
<View>
<TouchableOpacity
onPress={() => {
navigation.goBack();
}}>
GoBack
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setNewTab(true);
//Code for the push data in Redux store
}}>
NewTab
</TouchableOpacity>
</View>
)
}
export default App();
2
Answers
No need to use useEffect in this case, you component will automatically render after state will change.
like this
}
In your case, the useEffect is triggered when newTab changes, and the cleanup function is executed with the old value of newTab before the new value.
you can use a variable to store the previous value and compare it within the cleanup function.