31
loading...
This website collects cookies to deliver better user experience
useEffect
hook, than because very often we do want to execute something asynchronously. In most scenarios we are doing this when a component gets mounted. useEffect
but has a 3 different points. isMounted
functionuseEffect
. It has the dependency array, but the callback you pass in, will receive a isMounted
function. You can call this function whenever you want to check if the component is mounted or not. Ref
s using useRef
The hook stores the current state whether it is mounted or not. To get this state, we define a function that resolves with the mounted reference.
The hook calls the current callback. The callback can change but we call it only if the dependency array changes, so it works basically exactly like useEffect.
the callback now should check whether it should set a state based on the information isMounted()
returns.
const MyComponent = ({ id }) => {
const [status, setStatus] = useState();
const [data, setData] = useState();
useMountedEffect(async (isMounted) => {
setStatus("LOADIGN");
try {
const data = await fetchMyData({ id });
// only set state if we are still mounted
if (isMounted()) {
setData(data);
setStatus("DONE")
}
} catch (e) {
if (isMounted()) {
setStatus("ERROR")
}
}
}, [id])
}