Dependencies in useEffect in React
Now let's change the color by pressing a button. Let's create a state color for the color, giving it an initial value:
const [color, setColor] = useState('green');
Let's replace the string value with our state in useEffect and don't forget to add it to the list of dependencies in square brackets. Now the effect will be executed every time the state color changes:
function App() {
useEffect(() => {
document.body.style.backgroundColor = color;
}, [color]);
...
}
Let's now add a button to change the color to our component:
return (
<div>
<h1>React App</h1>
<button onClick={changeColor}>change</button>
</div>
);
Let's also add a click handler function that will change our color to orange:
function changeColor() {
setColor('orange');
}
Given a state with a username. Make it so that every time the name changes, the state value is written to the browser's local storage.