React의 useEffect() 후크 이해

DDD
풀어 주다: 2024-10-05 12:17:02
원래의
973명이 탐색했습니다.

React는 버전 16.8에서 Hook을 도입했으며 가장 일반적으로 사용되는 Hook 중 하나는 useEffect()입니다. useEffect() 후크를 사용하면 데이터 가져오기, DOM 업데이트 또는 구독 설정과 같은 함수 구성 요소에서 부작용을 수행할 수 있습니다.

useEffect() 작동 방식
useEffect() 후크는 두 가지 인수를 허용합니다:

  1. 함수: 실행될 효과입니다. 이 함수는 구성 요소가 렌더링(또는 다시 렌더링)된 후에 실행됩니다. 이것을 '부작용' 논리라고 생각하시면 됩니다.
  2. 선택적 종속성 배열: 이는 React에게 효과를 다시 실행할 시기를 알려줍니다. 빈 배열([])을 제공하면 효과는 초기 렌더링 후 한 번만 실행됩니다.

기본 구문:


useEffect(() => {
  // Your side effect code here
}, [dependencies]);


로그인 후 복사

예시 1: 데이터 가져오기


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;



로그인 후 복사

출력

Understanding the useEffect() Hook in React

예 2: 타이머 설정


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;



로그인 후 복사

출력

Understanding the useEffect() Hook in React

요약하자면:

  1. 데이터 가져오기, DOM 조작, 타이머 설정과 같은 작업에는 useEffect()를 사용하세요.
  2. 종속성 배열을 전달하여 효과가 실행되는 시점을 제어할 수 있습니다.
  3. useEffect() 콜백에서 함수를 반환하여 필요한 경우 항상 효과를 정리하세요.

위 내용은 React의 useEffect() 후크 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!