The useEffect hook helps us tap into the power of lifecycle methods within functional components without having to write class components.
This hook takes in a call back function as a parameter which basically contains the code we want to run every time the component re-renders. It is most commonly used to serve the function of a componentDidMount lifecycle method in order to communicate with a database or an API. However in this example, we will simply console log some information anytime the component re renders.
In order to use this, we do;
First we import {useEffect}
from react
at the top, then within the component we write out our code and it takes in the call back method that simply logs How to use the useEffectHook
. Now, everytime the page first loads , the useEffect hook is rendered.
It is important to note that by default, when the page first loads and on every new update or change to any state depending on the number of states we have in our application, the useEffect hook runs and this may lead to unintended consequences. As such, the hook takes in a second parameter that specifies exactly when we want this hook to run.
Lets add some state to our function component, using the useState
hook earlier discussed and create a new state we call person
. Now assume we want the data in our useEffect
Hook to only re render once on page load and whenever our person
state is updated using the setPerson
hook, we can add a second parameter to our useEffect
to specify this.
Look at the following code example:
Note how we added the second parameter [person]
in the useEffect
hook
in order to specify exactly when it renders.
In summary, the useEffect hook helps improve on the power of functional components and reduces the need to always write class based components.
Top comments (0)