All Articles

What is the UseEffect Hook?

In this article i’ll be writing about the useEffect Hook, what it is, the problems it can solve for you and how to use it in your react projects.

What are hooks?

Very quickly, hooks are Javascript functions that let you ‘hook’ into React state and access lifecycle features from functional components. Prior to hooks, state and lifecycle features could only be accessed from within class components. You can find further reading in the official react documentation.

React 16.8 introduced the new hooks api and it comes bundled with the following basic hooks

  • useState
  • useEffect
  • useContext

You can read more about them here

The useEffect Hook

The useEffect hook is an in-built hook that is used to introduce side-effects in our rect components. What’s a side-effect you ask? Good question. Simply put a side effect is an event that occurs within our component after there has been a change to the components internal state.

The useEffect hook helps us to orchestrate and manage such side-effects in a manner that is clean, easy to maintain and easy to test. Some practical examples of side-effects in our components are; Fetching data from an api, prop-drilling to a parent component, calling a function, logging, Dom manipulation with Refs, managing web sockets etc.

An example is given in the piece of code below.

    import React, {useEffect, useState} from "react";

    const emojis = ['🤣', '😶', ' 😒'];

    export default function App() {
      const [text, setText] = useState('');
      const [emoji, setEmoji] = useState(emojis[0]);

      useEffect(() => {
        setRandomEmoji();
      });

      function setRandomEmoji(){
        const randomEmoji = emojis[Math.floor(Math.random() * emojis.length)];
        setEmoji(randomEmoji);
      }

      function handleChange(e){
        setText(e.target.value);
      }

      return (
        <div className="App">
          <input value={text} onChange={handleChange}/>
          <p>{emoji}</p>
        </div>
      );
    }

The piece of code above updates the view with a random emoji whenever we type into the input field. This is achieved with the useEffect function on line 9 that takes an arrow function as a first argument, Whenever the component re-renders the function is called, thereby performing the side-effect.

For optimisations sake, If we only want to perform the update when a particular prop or state value changes, you can pass in said value in an optional dependency array like so

	useEffect(() => {
      setRandomEmoji();
  	}, [text]);

Whenever the state variable text changes the arrow-function is triggered thereby calling the setRandomEmoji() function. This mirrors the componentDidUpdate() lifecycle method.

So now that you have a basic understanding of the useEffect hook. Here’s a cheatsheet for use-cases and rules to follow when using the useEffect hook.

  • To run a side-effect in your application after a re-render or an update to the DOM:
useEffect(() => {
            performSideEffect();
        });

Not passing the second argument (ie the array of dependencies) tells react to call the function in the callback every time theres been a re-render

  • To run a side-effect on initial Mount only, the hook takes this form;

    useEffect(() => {
        performSideEffect();
      }, []);

    Passing an empty array as the second argument tells React that your side-effect doesn’t depend on values from state theres no need to trigger it after a re-render

  • To run a side-effect after a particular prop or state value has changed, the hook takes this form;

    useEffect(() => {
            performSideEffect();
        }, [value]);

    You can also pass in multiple elements into the array.

Conclusion

The useEffect hook is a powerful mechanism that helps us to make functional components a lot more powerful and makes applying side-effects much easier to reason out and structure. You can read this excellent article by Dan Abramov for a more detailed breakdown.

Thanks for Reading!