5

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?

Anand Rockzz
  • 6,072
  • 5
  • 64
  • 71
  • Please research more about Hooks dependencies. It seems to me that is the issue. https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect – Jerry Ben Mar 08 '21 at 21:11
  • Add `title` into your dependency for that hook. That should tell React to run this `useEffect` when `title` changes – Dominik Mar 08 '21 at 21:17
  • It shows intial value because of "stale closure". Related : https://stackoverflow.com/a/66435915/2873538 – Ajeet Shah Mar 08 '21 at 21:23

1 Answers1

3

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>
}
jean182
  • 3,213
  • 2
  • 16
  • 27
  • But when title changes, the console.log would prompt the old value, wouldn't it? How to access the new title inside the cleanup function? – Mario Eis Dec 29 '22 at 12:40
  • Indeed @MarioEis, it will prompt the old value. To get the most recent value, create a ref: `const titleRef = useRef()` followed by `titleRef.current = title`, outside of the effect (e.g. next to useState in the example) and then access the value in the cleanup function `console.log(titleRef.current)`. – dalvallana Feb 09 '23 at 15:03