Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

reactjs - how to use fresh state inside the useeffect, but execute cleanup on unmount only

AFAIK, in the React Function Component, one has to use useEffect for componentWillUnmount functionality like below:

useEffect(()=>{
  return console.log("component unmounting");
},[])

I am making a form page, and want to submit the progress when the user exits the page. So I am thinking of submitting inside the cleanup.

But if I don't put the formData state into the dependency array, the state will be stale during the cleanup.
And if I do put formData into the dependency array, the cleanup will run every time there is a change in formData.

How can I keep the state fresh, but run the cleanup only in the 'real unmount'?

const [formData, setFormData] = useState({
  input1: 'input1 default',
  input2: 'input2 default',
}); // track the form data


useEffect(()=>{
  return () => {
    axios.post(myFormSubmitURL, formData);
  }
}, []); // this will submit the stale data

useEffect(()=>{
  return () => {
    axios.post(myFormSubmitURL, formData);
  }
}, [formData]); // this will submit the data every time it changes
question from:https://stackoverflow.com/questions/65840197/how-to-use-fresh-state-inside-the-useeffect-but-execute-cleanup-on-unmount-only

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a react ref and additional effect to store a cache of your form state for use when the component unmounts.

const formDataRef = useRef();
const [formData, setFormData] = useState({
  input1: 'input1 default',
  input2: 'input2 default',
}); // track the form data


useEffect(()=>{
  return () => {
    axios.post(myFormSubmitURL, formDataRef.current); // <-- access current value
  }
}, []);

useEffect(()=>{
  formDataRef.current = { ...formData }; // <-- cache form updated data
}, [formData]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...