⊗jsrtPmHkUEI 4 of 47 menu

useEffect effect hook in React

To work with effects, the useEffect hook is used. Let's take a look at how it works.

First, let's import our hook:

import { useEffect } from 'react';

Let's create a App component that contains a title:

function App() { return ( <div> <h1>React App</h1> </div> ); } export default App;

Suppose we want to do something after rendering, like set the background color of the entire page. In this case, the external system would be the browser's DOM.

Let's apply our hook:

function App() { useEffect(() => { document.body.style.backgroundColor = 'green'; }, []); ... }

The second parameter is an array of dependencies. These include values ​​used by the component's functions. For now, we've left them empty. In this case, the color will be set to green only once after rendering. You can't remove the second parameter entirely, as your component may enter an infinite loop.

Use the useEffect hook to change the page title.

byenru