Effect Hooks in ReactJS

useeffect-hooks-in-reactjs

The Effect Hook allows you to perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

Read Hooks in ReactJS

UseEffect():

useEffect is a hook for encapsulating code that has ‘side effects’, if you are familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Note:- You can call useEffect as many times as you want.

Syntax:

The first argument function passed to useEffect, will run after the render is committed to the screen.

The second argument to useEffect is the array of values that the effect depends on.

Follow below code:

What does useEffect do?

By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed and call it later after performing the DOM updates. In this effect, we set the document title, we could also perform data fetching or call some other imperative API.

Why is useEffect called inside a Component?

Placing useEffect inside the component allows us to access the state variable or any props right from the effect.

Does useEffect run after every Render?

Yes, By Default, it runs both after the first render and after every update.

Let’s see example with complete code

In the above example, you can see we set state value of name, name2, salary, and salary2. State value is rendering with Employee Function Component. Here you can see, I added two buttons Salary Increment and Salary Decrement with onClick event handler {clickIncrement}, {clickDecrement}. In clickIncrement event handler, we are increasing salary value with 1. In clickDecrement event handler, We are decreasing salary with 1.

In useEffect, you can see two arguments. The first argument is a function and the second argument is an array of value [salary2]. It means when you will click on-increment event handler then it will not render. But as I passed salary2 as the second argument with useEffect hook then it will render every time when you click the Decrement button. Here use effect second argument validating that when information is required to render or not.

Related posts