Understanding the useEffect() Hook in React
React introduced Hooks in version 16.8, and one of the most commonly used Hooks is useEffect(). The useEffect() Hook lets us perform side effects in function components, such as fetching data, updating the DOM, or setting up subscriptions.
How useEffect() Works
The useEffect() Hook accepts two arguments:
- A function: This is the effect that will run. This function is executed after the component renders (or re-renders). You can think of this as the "side effect" logic.
- An optional dependency array: This tells React when to re-run the effect. If you provide an empty array ([]), the effect will only run once, after the initial render.
Basic Syntax:
useEffect(() => { // Your side effect code here }, [dependencies]);
Example 1: Fetching Data
import React, { useEffect, useState } from "react"; function DataFetchingComponent() { const [data, setData] = useState([]); const [error, setError] = useState(null); useEffect(() => { // Fetch data from an API fetch("https://jsonplaceholder.typicode.com/users") .then((response) => response.json()) .then((json) => setData(json)) .catch((err) => setError("Error fetching data")); }, []); return ( <div style={{ maxWidth: "1200px", margin: "0 auto", padding: "20px" }}> <h1 style={{ textAlign: "center", marginBottom: "20px", color: "#333" }}> Users Data </h1> <h2 style={{ textAlign: "center", marginBottom: "20px", color: "#333" }}> Understanding the useEffect() Hook in React By Sudhanshu Gaikwad </h2> {error ? ( <p style={{ color: "red", textAlign: "center" }}>{error}</p> ) : ( <table style={{ width: "100%", borderCollapse: "collapse", marginBottom: "20px", }} > <thead style={{ backgroundColor: "black", color: "white" }}> <tr> <th style={{ padding: "10px", textAlign: "left" }}>ID</th> <th style={{ padding: "10px", textAlign: "left" }}>Name</th> <th style={{ padding: "10px", textAlign: "left" }}>Username</th> <th style={{ padding: "10px", textAlign: "left" }}>Email</th> </tr> </thead> <tbody> {data.map((user) => ( <tr key={user.id} style={{ backgroundColor: user.id % 2 === 0 ? "#f2f2f2" : "white", borderBottom: "1px solid #ddd", }} > <td style={{ padding: "10px" }}>{user.id}</td> <td style={{ padding: "10px" }}>{user.name}</td> <td style={{ padding: "10px" }}>{user.username}</td> <td style={{ padding: "10px" }}>{user.email}</td> </tr> ))} </tbody> </table> )} </div> ); } export default DataFetchingComponent;
Output
Example 2: Setting up a Timer
import React, { useState, useEffect } from "react"; function TimerComponent() { const [count, setCount] = useState(0); useEffect(() => { const interval = setInterval(() => { setCount((prevCount) => prevCount + 1); }, 1000); return () => clearInterval(interval); }, []); return ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100vh", backgroundColor: "#f0f4f8" }}> <div style={{ backgroundColor: "#fff", borderRadius: "10px", padding: "30px 50px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)", textAlign: "center" }}> <h1 style={{ fontSize: "3rem", fontFamily: "Roboto, sans-serif", color: "#333", margin: "0" }}>{count} seconds</h1> <p style={{ marginTop: "15px", fontSize: "1.2rem", color: "#666" }}>Timer running with useEffect hook</p> </div> </div> ); } export default TimerComponent;
Output
To summarize:
- Use useEffect() for tasks like fetching data, manipulating the DOM, or setting up timers.
- You can control when the effect runs by passing a dependency array.
- Always clean up effects when necessary by returning a function from the useEffect()callback.
The above is the detailed content of Understanding the useEffect() Hook in React. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript
