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.
Syntax
Section titled “Syntax”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.
Example
Section titled “Example”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.
Best Practice
Section titled “Best Practice”- Use
useEffectto 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
StrictModeto help catch common Effect Hook issues during development.
Dive Deep
Section titled “Dive Deep”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
