You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React:如何让仅首个useEffect初始渲染,其余依依赖触发

解决方案

要实现仅第一个useEffect在初始渲染时执行,其余useEffect仅在依赖props变化时触发,核心是通过useRef标记是否为首次渲染,跳过非初始阶段不需要执行的逻辑。

改造思路

  1. 用useRef创建标记变量isFirstRender,初始值设为true,用来标识当前是否为首次渲染。
  2. 新增一个空依赖的useEffect,仅在首次渲染完成后将标记改为false。
  3. 在需要跳过首次渲染的useEffect开头添加判断:如果是首次渲染则直接返回,不执行后续逻辑;非首次渲染时再执行对应业务代码。

修改后的函数组件代码

import { useState, useEffect, useRef } from 'react';

function YourComponent(props) {
    const isFirstRender = useRef(true);
    const [patchTaskVal, setPatchTaskVal] = useState(/* initial value */); 
    const [startTime, setStartTime] = useState();
    const [endTime, setEndTime] = useState();
    // 补充原类组件中的其他状态
    // const [showValue, setShowValue] = useState(true);
    // const [progressValue, setProgressValue] = useState([]);

    // 标记首次渲染完成
    useEffect(() => {
        isFirstRender.current = false;
    }, []);
    
    // 仅在初始渲染时执行:同步props初始值到组件状态
    useEffect(() => {
        setPatchTaskVal(props.patchTaskVal);
        setStartTime(props.patchStartTime);
        setEndTime(props.patchEndTime);
    }, []);
    
    // 仅在props.patchTaskVal变化时执行(跳过初始渲染)
    useEffect(() => {
        if (isFirstRender.current) return;
        callValidation();
    }, [props.patchTaskVal]);
    
    // 仅在props.closeTask变化时执行(跳过初始渲染)
    useEffect(() => {
        if (isFirstRender.current) return;
        // setShowValue(false);
        // setProgressValue([]);
        setStartTime(new Date());
        setEndTime("");
    }, [props.closeTask]);
    
    // 仅在props.patchStartTime/endTime变化且endTime不为空时执行(跳过初始渲染)
    useEffect(() => {
        if (isFirstRender.current) return;
        if (props.endTime !== "") {
            setStartTime(props.patchStartTime);
            setEndTime(parseInt(props.endTime));
        }
    }, [props.patchStartTime, props.endTime]);

    // 组件其余渲染逻辑...
    return <div>Your Component Content</div>;
}

关键说明

  • useRef的标记值不会触发组件重新渲染,适合记录渲染周期内的状态。
  • 标记首次渲染完成的useEffect必须设置空依赖数组[],确保仅在初始渲染后执行一次。
  • 每个需要跳过初始渲染的useEffect都要添加标记判断,严格对应类组件中componentDidUpdate的触发逻辑。

内容的提问来源于stack exchange,提问作者Dante1021

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:35:39