Dependencies Array Usage for Components and Functions

Learn more benefits of using the dependencies array for creating decoupled React components. This lesson will also explore the details for managing local functions with the “useEffect” hook.

Using the dependencies array to update components

The previous example demonstrated how to use the useEffect hook to create logic based on changes in props or state.

Let’s explore this in more detail.

Assume you have several decoupled React components including:

  • Global state to hold profile data
  • Header to fetch greeting message from API
  • Some forms to update profile

As seen above, useEffect is handy when the user changes the name through one of the forms and the global state is updated. Header will simply fetch the new message when the name changes.

The following snippet shows the same:

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

const Header = ({ name }) => {
  // Name is a prop or external dependency
  const [message, setMessage] = useState('');

  useEffect(() => {
    loadMessage(name);
  }, [name]);

  const loadMessage = nickName => {
    // fetch and set message
  };

  return (
    <h1>{message}</h1>
  );
};

Each time name is updated, the useEffect function will run and load the new message.

Get hands-on with 1400+ tech skills courses.