于永雨的学习笔记
  • 学海无涯
  • 前端基础
    • HTML
      • 语义化标签
      • script标签中defer和async
      • 本地存储
      • 拖拽
      • Web Workers
      • WebSocket
    • CSS
      • 盒模型和box-sizing
      • BFC(块级格式化上下文)
      • 浮动和清除浮动
      • 伪类和伪元素
      • 2倍图、3倍图
      • flex
      • 水平居中、垂直居中
      • 经典布局
        • 两列布局
        • 三列布局
      • 经典实践
      • CSS样式隔离
      • Less vs Sass
    • JavaScript
      • ES
        • 数据类型
          • 1-string
          • 2-number
          • 3-boolean
          • 4-null
          • 5-undefined
          • 6-symbol
          • 7-object
          • 常见类型判断
          • 浅拷贝、深拷贝
        • 数据集合
          • Array
          • 类数组对象
          • Map、WeakMap
          • Set、WeakSet
          • 常见遍历方式
        • 变量
          • 修饰符
          • 变量提升
        • 函数
          • apply、call、bind
          • new
          • this
          • 箭头函数
          • 闭包
          • 防抖和节流
          • 柯里化
        • 原型
          • 原型链
        • 异步
          • 单线程&事件循环
          • 常见异步
          • Promise
            • all和allSettled
            • race和any
            • resolve和reject
        • 模块化
        • 版本特性一览表
      • DOM
        • DOM事件
        • 事件分类
      • BOM
    • TypeScript
    • 浏览器
      • 页面渲染
      • 重绘和回流
      • 跨域
      • 垃圾回收
      • 取消请求
    • Web API
      • EventSource
      • XMLHttpRequest
      • WebSocket
      • IntersectionObserver
  • 前端框架
    • Vue
      • 2.0
        • 列表渲染的key
        • 生命周期
        • diff算法
      • 3.0
        • 改变
        • provide/inject
        • 组件间可复用逻辑封装
        • diff算法
    • React
      • Component
      • Props
      • State
      • Context
      • Effect
      • Hooks
        • hook依赖列表
        • useMemo
        • useCallback
        • useEffect
      • API
        • memo
      • 子组件的无效渲染
      • 组件在开发模式下渲染两次
    • Vue-Router
    • Taro
    • Qiankun
  • 前端方案
    • 错误上报
    • 性能优化
    • 长列表优化原理
    • H5移动端适配
  • 工程化
    • 前端
      • 防止package-lock.json删除
      • 打包ESM和CommonJS
      • babel
      • webpack
      • pnpm
      • 多包管理
      • vite
      • 各种base
    • 服务端
      • Maven
  • 小程序
    • 小程序历史
    • 双线程架构
    • 生命周期
    • 更新机制
  • 服务端
    • Redis
    • Node.js
      • 核心
      • 进程守护
      • Koa
    • Java
      • 安装与配置
    • Restful API
  • DevOps
    • Nginx
    • Docker
      • 核心概念
      • 基础命令
    • K8s
    • Linux
      • shell及脚本
      • 文件目录操作
      • vi/vim
  • 计算机基础
    • 数据结构
      • 栈(Stack)
      • 队列(Queue)
      • 数组(Array)
      • 链表(Linked List)
      • 树(Tree)
      • 图(Graph)
      • 堆(Heap)
      • 散列表(Hash Table)
    • 算法
      • 查找
      • 排序
  • 计算机网络
    • 基础
    • TCP
      • 建立连接(三次握手)
      • 断开连接(四次挥手)
    • UDP
    • HTTP
      • HTTP/2
      • HTTPS
    • 常见网络攻击
      • XSS
      • CSRF
      • DDos
      • MITM
    • 浏览器缓存
  • 经典面试题
    • 箭头函数this-1
    • 箭头函数this-2
    • 数组转树
    • 控制并发数
    • 动态规划-二维数组全排列
    • 柯里化
Powered by GitBook
On this page
  • 作用
  • 示例
  • 关键点
  1. 前端框架
  2. React
  3. Hooks

useEffect

react的逃生舱

作用

和非React的外部系统交互,比如发起请求(建立服务器连接)、调用浏览器API(设置定时器)等

useEffect(setup, dependencies?)

setup函数包含两部分:

  • setup code:组件挂载(插入到DOM中)时调用

  • cleanup code(可选):组件卸载(从DOM中移除)时调用,主要用于清除遗留逻辑,比如清除定时器、断开服务器连接等

执行顺序:

  • 首次挂载(开发模式):setup => cleanup => setup

  • 首次挂载(生产模式):setup

  • 重新渲染:cleanup(旧值) => setup(新值)

  • 组件卸载:cleanup

After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values.

示例

import { useEffect } from 'react';
import { createConnection } from './chat.js';

function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://localhost:1234');

  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);
    connection.connect();
    return () => {
      connection.disconnect();
    };
  }, [serverUrl, roomId]);
  // ...
}

关键点

  • 只可在组件顶层执行,不可放到循环或条件中

  • 如果不和外部系统通信,没必要使用Effect

  • 使用useLayoutEffect代替:(没理解~)

PrevioususeCallbackNextAPI

Last updated 1 year ago

If your Effect wasn’t caused by an interaction (like a click), React will let the browser paint the updated screen first before running your Effect. If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), replace useEffect with

Even if your Effect was caused by an interaction (like a click), the browser may repaint the screen before processing the state updates inside your Effect. Usually, that’s what you want. However, if you must block the browser from repainting the screen, you need to replace useEffect with

useLayoutEffect.
useLayoutEffect.