The task is to create a useIsMounted hook to determine if a component is mounted. The boilerplate code:
import React from 'react';
export function useIsMounted(): () => boolean {
// your code here
}
// to try your code on the right panel
// export App() component like below
// export function App() {
// ...
// return <div>BFE.dev</div>
// }
The first step is to create a reference that holds the component state
const isMounted = useRef(false)
The component is either going to be mounted or not. As a result, the only states are either true or false. When the component is mounted, the .current value of the ref is set to true when the app is rendered.
useEffect(() => {
isMounted.current = true
})
Then, the state is set to false before the app is rendered again.
return () => {
isMounted.current = false
}
Finally, a function is returned to be able to call isMounted() in async code
return () => isMounted.current
The final code looks like this:
import React, { useEffect, useRef} from 'react';
export function useIsMounted(): () => boolean {
// your code here
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
}
}, [])
return () => isMounted.current
}
// to try your code on the right panel
// export App() component like below
// export function App() {
// ...
// return <div>BFE.dev</div>
// }
That's all folks!
Top comments (0)