I went through one simple use of the Clean up function. On change of Input text value, we get an alert of the value we have in the text box.
I have code like this
import React, { useState, useEffect } from "react";
function App() {
const [value, setValue] = useState("");
//Waits for a period of time then resolves
function timeout(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const myAlert =async () =>{
await timeout(1000);
alert(`A name was changed: ${value}`);
}
useEffect(() => {
let isCancelled = false;
const handleChange = async () => {
if (!isCancelled) {
await myAlert();
}
};
handleChange();
return () => {
isCancelled = true;
};
}, [value]);
return (
<div className="App">
<div>
<form>
<label>
Name:
<input
type="text"
value={value}
onChange={(event) => setValue(event.target.value)}
/>
</label>
<input type="submit" value="Submit" />
</form>
</div>
</div>
);
}
export default App;
Here we are calling myAlert in useEffect. SO, how we can use the Cleanup function with this type of case, where we are not changing the state in useeffect but we call an async function in use effect where we change the state.
codesandbox Link is here : https://codesandbox.io/s/strange-greider-7k1svi?file=/src/App.js
I'm not sure why do you try to use the cleanup function. In a normal case, you have to set a state in some condition. Effects are controlled via their dependencies, not by the lifecycle of the component that uses them.
Anytime dependencies of an effect change, useEffect will cleanup the previous effect and run the new effect.
import React, { useState, useEffect } from "react";
function App() {
const [value, setValue] = useState("");
const [isCancelled, setsCancelled] = useState(false);
//Waits for a period of time then resolves
function timeout(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const myAlert = async () => {
await timeout(1000);
alert(`A name was changed: ${value}`);
};
useEffect(() => {
const handleChange = async () => {
if (isCancelled) {
setsCancelled(true)
await myAlert();
}
};
handleChange();
}, [value]);
return (
<div className="App">
<div>
<form>
<label>
Name:
<input
type="text"
value={value}
onChange={(event) => setValue(event.target.value)}
/>
</label>
<input type="submit" value="Submit" />
</form>
</div>
</div>
);
}
export default App;