score:12

Accepted answer

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)
}, [])

score:0

thedude's approach is right. Tweaked it a bit, for this particular usecase as input ref is always same :

function SavedInput() {
  const inputEl = useRef(null);
  React.useEffect(() => {
    return () => {
      save(inputEl.current.value);
    };
  }, []);

  return (
    <div>
      <input ref={inputEl} />
    </div>
  );
}

By this way you'll avoid re-render as you are not setting any state.


Related Query

More Query from same tag