useEffect hook in React
What does the useEffect hook in React do? Why do I need it? These are some questions I've asked myself when learning React. I'm going to give you a quick post on how to effectively implement the useEffect hook into your new React app and how it can save you some headaches in the future.
In order to start using the hook you must first import it into your app.
import 'React', { useEffect } from 'react';
Now inside of your App component class you can use the imported hook. useEffect takes a function as it's first parameter. This function will get invoked when your component "did mount", gets "updated" and "unmounted" inside your application....everytime.
const App = () => {
useEffect(() => {
//what should I do in here?
});
return (
<div></div>
);
};
The useEffect hook is a perfect place to make HTTP requests inside your application but since the DOM gets updated frequently in a React project anything you do inside this function will cause infinite loops or unwanted problems inside your app that can cause you to start chasing bugs in your code.
So here is how you control how often the function inside your useEffect gets invoked.
useEffect allows you to give it a second parameter. The second parameter must be an array. There are two different ways you can utilize this inside your app.
const App = () => {
useEffect(() => {
//make an http request
}, []);
return (
<div></div>
);
};
As you can see I have given useEffect an empty array. Because the array is empty useEffect will now only run the function when the component mounts after the DOM has been updated.
So what if you want to run this function when some value changes inside your component that your app relies on? There is a solution for that too.
Say for instance you are making an api call inside your useEffect hook but you need to update some data in your component on the fly. You can tell useEffect to run the function if something changes in your component by adding those values inside the array we gave it.
const App = () => {
useEffect(() => {
//make an http request
}, [someValue]);
return (
<div></div>
);
};
Now the useEffect will run when the component mounts and it will also run this function if "someValue" ever gets changed inside your component. You can add as many values inside the array that you want useEffect to watch.
If you want more information on using the useEffect hook or you have run into problems using it inside your application feel free to book a session with me or give me some feedback and I will keep updating this post with more information.
Regarding the array you pass as a second argument, what if
someValue
is an object or an array and it doesn’t change? Wouldn’t this still cause the function inside useEffect to be called because the object/array is allocated to a different place in memory with every re-render?