October 15, 2024

React Hooks – Effect Hook

The Effect Hook helps you perform side effects in a functional component.

  1. What are Side Effects
  2. The Effect Hood Example
  3. Conditionally Run an Effect
  4. Run useEffect only Once

 

1. What are side effect?

Side effect or just ‘effects’ are operations that are performed as a result of changes in the state of a component.

For example:

  • fetching data from API when component mounts
  • changing DOM element, say the title of the page when component updates
  • performing some cleanup when components unmounts

As you know, lifecycle methods are not available in functional components. Therefore, the effects hooks help you mimic lifecycle method inside a functional component.

Let’s take an example

 

2. Effects Hook Example

In this example,

  • we would like to initially set the document title when the document loads.
  • Next we would like to update the document title whenever the component updates.

Before we present this example, let’s quickly mention how the effects hook work

 

How the Effect Hook Work

Just like useState(), useEffect() is also a function. So need to call it. Then we need to pass in a parameter. This parameter is a function that will be executed after every render of the component.

Meanwhile, the useEffect() returns void.

function EffectsDemoClass() {

    const [count, setCount] = useState(0)

    useEffect(()=>{
        document.title = `Clicks ${count}`
    })

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click Here
            </button>
        </div>
    )
}

For the above code, the document title is set at every render including the initial render.

 

3. Conditionally Run an Effect

We’ll adjust the previous example by adding a textfield. This textfile would hold a name state variable. And of course, we’ll use a new useState() to control this textfield.

So in the onChange event of the textfield, we’ll update the name variable.

The problem here is this: when the text is changed, the useEffect() is executed regardless of the fact that the document title has remained unchanged.

Now to solve this, we need to somehow tell useEffect() to run conditionally only when a particular state changes.This is achieved by giving useEffect() a second parameter. This parameter is an array that holds the states to watch for changes.

So I have made the changes. Here’s the new function

function EffectsDemoClass() {

    const [count, setCount] = useState(0)
    const [name, setName] = useState('')

    useEffect(()=>{
        console.log('Updating Document Title')
        document.title = `Clicks ${count}`
    }, [count]) //run useEffect only when count changes

    return (
        <div>
            <input type="text" 
                value={name} onChange={(e) => setName(e.target.value)}>
            </input>

            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click Here
            </button>
        </div>
    )
}

In this case, the document title is set only when the count changes.

In summary, in order to conditionally run useEffect(), we must specify a second parameter which is the state to monitor for changes.

 

4. Run useEffect() Only Once

Assuming we want to run an effect only once. That is during the first render. In order words, you want to mimic componentDidMount. What you’ll do is to simply pass an empty array to useEffect() as its second parameter.

In this way, the effect is run only once and not called during re-renders.

useEffect(()=> {
    //function body
},[]) //run useEffect only once

I recommend you try it with the previous example.

More on Effect Hook in the next tutorial.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments