Skip to content
Node.js Sounds Complicated? This Article Makes It Click

useEffect in React – How to Use Effect Hooks in Components

The useEffect Hook lets function components perform side effects outside React.

This post is a quick reference guide to the Code React Sweetly book.

The useEffect Hook accepts two arguments. Here’s the syntax:

useEffect(callback, array);
  • callback: The required setup function for the Effect Hook.
  • array: (Optional) The reactive dependencies list that indicates when React runs the callback.
import { useState, useEffect } from "react";
function AboutCompany() {
const [age, setAge] = useState(5);
useEffect(() => {
document.title = `🥳🎁🎉 It's CodeSweetly's birthday! 🎉🎁🥳`;
});
return (
<div>
<h3>CodeSweetly is {age} years old!</h3>
<button type="button" onClick={() => setAge(age + 1)}>
Click to update age
</button>
</div>
);
}
export default AboutCompany;

The useEffect code updates the browser’s title after the UI finishes rendering.

  • Use useEffect to connect with things outside your React app, such as APIs or timers. If your code has no side effects, you likely do not need it.
  • Avoid adding values to the dependency array unless your effect uses them. Include only the state and props needed to prevent unnecessary re-runs.
  • Declare static objects and functions outside components. Place dynamic ones inside your Effect Hook.
  • When depending on object props, list each primitive value used in your effect instead of the entire object.
  • Use StrictMode to help catch common Effect Hook issues during development.

The Effect Hook is powerful but often misunderstood. The Code React Sweetly book covers these key concepts:

  • The different types of Effects in React and when to use them
  • How to identify Effects that need cleanup and those that don’t
  • How to clean up Effects properly to avoid memory leaks
  • When to trigger effects for optimal performance

A Beginner's Guide to React: Learn JSX, Hooks, and Real-World App Development