I am using React 16.8.6 and hooks. I am new to hooks.
I have a component loaded in a route I need to add a body class to. When the user leaves this page, I need the class removed. I am using
useEffect(() => {
document.body.className = 'signin';
}, []);
This correctly adds the class to the body tag. Except when I navigate to another page, the class remains. If I reload the second page it's gone.
How do I remove the class when the component unmounts when the route changes?
If you don't specify it, the effect runs after each render. If it's empty ( [] ), the effect runs once, after the initial render.
Using useEffect to apply lifecycle methods in functional components. In class components, we have lifecycle methods to perform actions in a specific lifecycle stage of our component. For us to do something similar and perform side effects in our functional components, the React team created the useEffect Hook.
From the previous question, we found out that componentDidMount doesn't have the same behavior with useEffect hook, because componentDidMount invoked synchronously before the browser paints the screen, while useEffect is invoked asynchronously after the browser has already painted the screen.
If your effect returns a function, it will act as a cleanup.
useEffect(() => {
document.body.classList.add('signin');
return function cleanup() {
document.body.classList.remove('signin');
};
}, []);
You can check out Effects with cleanup in the documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With