Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: add body class only to certain components in useEffect hook?

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?

like image 396
Steve Avatar asked Jul 07 '19 23:07

Steve


People also ask

What happens if you don't specify the dependencies list in useEffect?

If you don't specify it, the effect runs after each render. If it's empty ( [] ), the effect runs once, after the initial render.

Does useEffect work in class components?

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.

What is the difference between useEffect and componentDidMount?

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.


1 Answers

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

like image 184
d4vsanchez Avatar answered Nov 15 '22 07:11

d4vsanchez