Reputation: 6658
I have a field like so
const SimpleReactComponent = (props) => {
const [title, setTitle] = useState('DEFAULT')
useEffect(() => {
return () => {
// unmount
console.log(`[${title}] while unmounting`)
}
}, [])
return <TextInput value={title} onChangeText={title => setTitle(title)}></TextInput>
}
When I modify the title
field and navigate away from this component, it still prints the following
[DEFAULT] while unmounting
While I'm expecting the newly modified value instead of DEFAULT
.
How to capture the changes while component is unmounting?
Upvotes: 5
Views: 2550
Reputation: 3505
You need to add the title value in the dependency array of the hook. If not the hook will only run when the component mounts and will log the initial value in that time. Adding the title in the dependency array will make the useEffect listen everytime the title value changes and it will display the correct value when you unmount the component.
const SimpleReactComponent = (props) => {
const [title, setTitle] = useState('DEFAULT')
useEffect(() => {
return () => {
// unmount
console.log(`[${title}] while unmounting`)
}
}, [title])
// Dependency array need the title to run everytime the value changes and when the unmount runs it will have the latest value!
return <TextInput value={title} onChangeText={title => setTitle(title)}></TextInput>
}
Upvotes: 3