Skip to content
On this page

useEffect

方便管理生命周期的 Hook,立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行。

Demo

Please open console
count: 0
state: 0
<template>
<div>Please open console</div>
<div>count: {{ count }}</div>
<div>state: {{ state }}</div>
<button @click="inc()">incCount</button>
<button @click="dec()">decCount</button>
<button @click="incState()">incState</button>
</template>

<script setup lang="ts">
import { useState, useCounter, useEffect } from 'v3-use'
const [count, { dec, inc }] = useCounter(0)
const [state, setState] = useState(0)

const incState = () => {
setState(c => c + 1)
}

useEffect(() => {
console.log('mounted')
return () => {
console.log('breforeUnmont')
}
}, [])

useEffect(() => {
console.log('updated')
return () => {
console.log('updated 销毁')
}
})

useEffect(() => {
console.log('watch state:', state.value)
return () => {
console.log('执行销毁函数')
}
}, [state])

useEffect(() => {
console.log('watch count:', count.value)
}, [count])

useEffect(() => {
console.log('watch count and state:', count.value, state.value)
}, [count, state])
</script>

Usage

// onMount、onBeforeUnmount
useEffect(() => {
  console.log('mounted')
  return () => {
    console.log('beforeUnmount')
  }
}, [])

// onUpdated
useEffect(() => {
  console.log('updated')
})

// watch state
useEffect(() => {
  console.log('watch state:', state)
}, [state])
// onMount、onBeforeUnmount
useEffect(() => {
  console.log('mounted')
  return () => {
    console.log('beforeUnmount')
  }
}, [])

// onUpdated
useEffect(() => {
  console.log('updated')
})

// watch state
useEffect(() => {
  console.log('watch state:', state)
}, [state])

Reference

Type Declarations

declare const UNDEFINED_VOID_ONLY: unique symbol
export declare type Destructor = () => void | {
  [UNDEFINED_VOID_ONLY]: never
}
export declare type EffectCallback = () => void | Destructor
export declare type DependencyList = ReadonlyArray<any>
export declare function useEffect(
  effect: EffectCallback,
  deps?: DependencyList
): void
declare const UNDEFINED_VOID_ONLY: unique symbol
export declare type Destructor = () => void | {
  [UNDEFINED_VOID_ONLY]: never
}
export declare type EffectCallback = () => void | Destructor
export declare type DependencyList = ReadonlyArray<any>
export declare function useEffect(
  effect: EffectCallback,
  deps?: DependencyList
): void