Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook - Use effect on component unmount only, not when dependency updates

I'm trying to build an input component using React Hooks that hits a remote server to save an updated value on component unmount only.

The remote server call is expensive, so I do not want to hit the server every time the input updates.

When I use the cleanup hook in useEffect, I am required to include the input value in the effect dependency array, which makes the remote API call execute on each update of the input value. If I don't include the input value in the effect dependency array, the updated input value is never saved.

Here is a code sandbox that shows the problem and explains the expected outcome: https://codesandbox.io/s/competent-meadow-nzkyv

Is it possible to accomplish this using React hooks? I know it defies parts of the paradigm of hooks, but surely this is a common-enough use case that it should be possible.

like image 405
Everrip Avatar asked Oct 31 '19 15:10

Everrip


1 Answers

You can use a ref to capture the changing value of your text, then you can reference it in another useEffect hook to save the text:

const [text, setText] = useState("");
const textRef = React.useRef(text);

React.useEffect( () => {
  textRef.current = text;    
}, [text])

React.useEffect( () => {
  return () => doSomething(textRef.current)
}, [])
like image 163
thedude Avatar answered Oct 11 '22 13:10

thedude