React’s useEffect hook has indeed made life a lot easier. But there are times when you would most certainly miss the fine-grained control class-based components give you over a component’s lifecycle. One such time is when you want to perform a side effect when a component’s state changes.
Of course, you can pass the state variable as a dependency into the useEffect hook but the problem is the callback function gets called during the initial render as well.
Take this little example. Let’s say I have an app that has a button. Once the button is clicked, I need to display a text that says “The button has been pressed!”. A simple way of doing this is to have a Boolean state value that will be set to true
once the button is clicked. The text can be displayed only if the Boolean value is true
.
However, for the sake of using the useEffect hook, let’s have two state values. Let me name the first state “press” and the second state “pressed”. Now, once the button is clicked, the press
state is set to true. Then let’s call the useEffect hook and pass a callback function that would set pressed
to true when press changes. The text should be shown only if pressed
is set to true.
export default function App() {
const [press, setPress] = useState(false);
const [pressed, setPressed] = useState(false);
useEffect(() => {
setPressed(true);
}, [press]);
return (
<div className="App">
{pressed && <div>The button has been pressed!</div>}
<button
onClick={() => {
setPress(true);
}}
>
Click!
</button>
</div>
);
But on running the app, you will realize that the text is shown even before the button is clicked. The reason? Well, useEffect’s callback function gets called not only when one of the dependencies changes but also during the initial render.
#react #front-end-development #frontend #reactjs