useEffect Dependency Array, Part 1

Understanding the Dependency Array

By default, a useEffect hook runs after every render. However, in many cases, you may want to control when it runs. You can achieve this by using its optional second argument: the dependency array.

Learning Goals

By the end of this reading, you should be able to:

How the Dependency Array Works

A useEffect hook always runs after the initial render. If a dependency array is provided, the hook will run again only when one of its dependencies changes.

Example:


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

React uses Object.is() to determine if elements in the array have changed.

Basic Example

Consider the following component:


function App() {
  const [num, setNum] = useState(0);

  useEffect(() => {
    console.log("App has rendered");
  });

  return (
    <>
      

Number: {num}

); }

Each time the button is clicked, num updates, triggering a re-render and causing the useEffect to log a message.

Using an Empty Dependency Array

If an effect has no dependencies, an empty array ([]) ensures it runs only once after the first render:


useEffect(() => {
  console.log("App has rendered");
}, []);
    

More Complex Example

Consider an app that renders a number and includes buttons to update the number and toggle visibility:


function App() {
  const [num, setNum] = useState(1);
  const [show, setShow] = useState(true);

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

  return (
    <>
      

The number is {num}

{show &&

{num} doubled is {num * 2}

} ); }

Since there is no dependency array, the effect runs after every re-render, even when toggling the visibility.

Adding Dependencies to the Array

To prevent unnecessary re-renders, we add num to the dependency array:


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

Now, the effect will only run when num changes.

Dependent Variables

Variables that depend on other variables must also be included:


function App() {
  const [num, setNum] = useState(1);
  const message = `The number is ${num}`;

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

Since message depends on num, it should be included in the dependency array.

What You Have Learned

In this reading, you explored:

Further Exploration

To continue learning, visit:

Conclusion

Using the dependency array effectively allows you to optimize performance and avoid unnecessary re-renders in your React applications.