React Hooks Pt. II - useEffect

·

2 min read

What are hooks

Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions that "hook into" React state and lifecycle features from function components. It does not work inside classes.

What is useEffect

The useEffect hook runs a function for every single render/side effect of the application. Since it doesn't return anything to us, all we do is pass it a function like so:

useEffect(() => {
    console.log('useEffect');
})

Dependencies

There are times when you don't want useEffect to run after every single render. This is where the dependency array comes in. This array is passed in after the callback function but within the useEffect hook as a second argument like so:

  • empty dependency array

    useEffect(() => {
      console.log('useEffect');
    },[])
    

    Passing an empty array will trigger the useEffect to run once at the initial render of the application. It will not run again despite the number of re-renders that may occur after the initial render.

  • passing a dependency to the array

import { useState, useEffect } from "react";

const App = () => {
  const [name, setName] = useState("Pikachu");

  useEffect(() => {
    console.log('useEffect');
  },[name])

  return (
    <div>
      <p>{name}</p>
      <button onClick={() => setName("Raichu")}>Evolve pokemon</button>
    </div>
  );
};

export default App;

In the above code snippet, when name is passed in the array, useEffect will run both at the initial render of the application and when name is triggered. Note: since the name state changes only omce (unlike a toggle effect), continuously clicking on the button without any additional state changes to name will not trigger useEffect.

Uses of the useEffect hook

  1. Fetching data from an API

Also read: