Understanding the useEffect Hook: simple examples

useEffect is one of the most common Hooks in React. I will present three simple examples to understand this function. Here we go.

Infinite rerender

Without secondary arguments, useEffect executes indefinitely:

jsx
import React, { useEffect } from 'react';

const Test = () => {

    useEffect( () => {
    
        console.log('Hi 👋');
        // Hi 👋
        // Hi 👋
        // Hi 👋
        // Hi 👋
        // ...
        // 'Hi 👋' is printed on every render
        
    });
    
}

export default Test;

One time execution

With an empty array as secondary argument, useEffect executes one time:

jsx
import React, { useEffect } from 'react';

const Test = () => {

    useEffect( () => {
    
        console.log('Hi 👋');
        // Hi 👋
        // 'Hi 👋' is printed only on first render
        
    }, []);
    
}

export default Test;

Execution depending on parameter

With an array containing a parameter as secondary argument, useEffect executes whenever this parameter changes:

jsx
import React, { useState, useEffect } from 'react';

const Test = () => {

    const [clicks, setClicks] = useState(0); 

    useEffect( () => {
    
        console.log('Hi 👋, you clicked the button ' + clicks + ' time(s).');
        // Hi 👋, you clicked the button 0 time(s).
        // Hi 👋, you clicked the button 1 time(s).
        // Hi 👋, you clicked the button 2 time(s).
        // Message is printed when button is clicked
        
    }, [clicks]);
    
    return (
        
        <button onClick = {() => setClicks(clicks + 1)}>Click me</button>
        
    );
}

export default Test;

React compares the array passed as parameter in useEffect. If the array is different between two renders, function will be executed.

That's why passing an empty array [] prevents to execute the function more than once.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.