Reputation: 127
I am using useState inside Dialog in React Material UI.
and I use useCallBack Function like this.
const [count,setCount] = React.useState({
count: 0
})
const countCallback = useCallback(
() =>
setCount({
...count,
count : count.count + 1
}),[setCount,count])
It shows incremented number when I click increment Button to execute this Callback in ChildComponent.
But when I closing Dialog and open Dialog again, count reset to 0.
Is there any way I can memorize count inside dialog? I don't want to use Redux.
Upvotes: 0
Views: 309
Reputation: 107
Issue is, when you close the dialog, Dialog component unmounts due to which on opening the component again value of count
sets to 0.
What you can do is, Send the value to parent component everytime it is changed. In parent component
store the value in state/local storage
and pass the value as a prop
to dialog component.
Upvotes: 0
Reputation: 126
If you want to persist the code you have used you can set the state in parent component, send that state as a props to child component and return the new value from the child component back to parent component.
Following link will help you to pass data from child to parent component in react: https://stackoverflow.com/a/44467773/8057264
Using this approach you can maintain the lastest count in your application.
Upvotes: 0
Reputation: 3690
You can use localstorage for it and use it to get the initial value of count at component mounting using useEffect
.
useEffect(() => {
const initialCount = localstorage.getItem("count"); //given that u name the localstorage variable as count when setting item //
if(initialCount){
setCount({count: initialCount})
}
},[])
You can use another useEffect to set the value of count or you can do it just before setting the state.
Upvotes: 1