跳转至

React Native 常用 Hooks 全面教程

从"什么是 Hook"到"最佳实践",配 12 个可直接运行的示例,一次讲透 React Native 中最常用的 9 个核心 Hook 与 3 个 RN 专属 Hook。


目录

  1. 什么是 Hook
  2. 为什么用 Hook
  3. Hooks 的优缺点
  4. 如何使用 Hook:两条铁律
  5. 常用 Hooks 详解(附可运行示例)
  6. 完整可运行 Demo
  7. 最佳实践

1. 什么是 Hook

Hook(钩子)是 React 16.8 引入的一组函数,让你可以在函数组件里"钩入" React 的状态(state)、生命周期、上下文等能力,而不用去写 class 组件。

React Native 完全基于 React 构建,所以 Hooks 在 RN 里与在 Web 端使用方式完全一致——所有核心 Hook 你都可以直接用。所有 Hook 都以 use 开头(如 useState、useEffect)。

一句话理解:Hook 就像把「会变化的零件」和「副作用」塞进函数组件里的插槽。函数组件本身只负责"根据 props 和 state 返回 UI",而 Hook 让这个纯粹的函数拥有记忆(state)和生命周期感知(effect)。

举个例子,同一段「计数」逻辑,用 class 组件和用 Hook 的函数组件写出来是这样:

Class 组件写法(旧):

import React, { Component } from 'react';
import { View, Text, Pressable } from 'react-native';

interface State {
  count: number;
}

export default class Counter extends Component<{}, State> {
  constructor(props: {}) {
    super(props);
    this.state = { count: 0 };
    this.handlePress = this.handlePress.bind(this); // 手动绑定 this
  }

  handlePress(): void {
    this.setState({ count: this.state.count + 1 });
  }

  componentDidMount(): void {
    console.log('组件挂载了');
  }

  render() {
    return (
      <View>
        <Text>计数:{this.state.count}</Text>
        <Pressable onPress={this.handlePress}>
          <Text>+1</Text>
        </Pressable>
      </View>
    );
  }
}

Hook 函数组件写法(新):

import React, { useState, useEffect } from 'react';
import { View, Text, Pressable } from 'react-native';

export default function Counter() {
  const [count, setCount] = useState<number>(0);

  useEffect(() => {
    console.log('组件挂载了');
  }, []);

  return (
    <View>
      <Text>计数:{count}</Text>
      <Pressable onPress={() => setCount((c: number) => c + 1)}>
        <Text>+1</Text>
      </Pressable>
    </View>
  );
}

核心变化:没有 this、没有构造函数、没有 bind;状态通过 useState 声明,生命周期通过 useEffect 表达。代码更短、更直白。

Hooks 解决了什么历史问题

在 Hooks 出现之前,想让组件拥有状态和生命周期,只能写 class 组件,并且面临几大痛点:

  • this 绑定麻烦:方法里到处是 .bind(this) 或箭头函数,容易出错。
  • 逻辑被生命周期切碎:同一件事的"开始/清理"要拆到 componentDidMount 和 componentWillUnmount 两个地方。
  • 状态逻辑复用难:想复用一段逻辑只能靠高阶组件(HOC)或 render props,会层层嵌套,形成"地狱回调式"的组件树。

2. 为什么用 Hook

使用 Hooks 的核心理由可以归结为四点:

理由一:让相关逻辑聚在一起

class 组件中,一次"订阅"往往要拆开写在 componentDidMount(订阅)、componentDidUpdate(更新)、componentWillUnmount(取消订阅)三个方法里。用 useEffect 后,这三件事在一个地方写,且能自动处理依赖变化。

理由二:逻辑复用不再靠嵌套

把一段可复用的逻辑抽成自定义 Hook(名字以 use 开头),任意组件直接调用即可,没有 HOC 的嵌套地狱。这在 React Native 中尤其重要——比如"监听键盘弹起""使用网络状态""获取设备方向"这类逻辑,都可以抽成自定义 Hook 复用。

理由三:告别 this,代码更简洁

函数组件 + Hooks 没有 this 指向问题,不需要手动绑定,心智负担更低,也更容易被 linter 和类型检查(TypeScript)理解。

理由四:React 官方推荐的现代写法

自 React 16.8 起,官方文档明确推荐函数组件 + Hooks 作为首选写法。RN 0.59+ 版本完全支持,新项目默认全是函数组件。学习 Hooks 是在跟 React / RN 的演进方向保持一致。


3. Hooks 的优缺点

优点 缺点 / 注意点
代码更简洁:无 this、无构造函数、样板代码大幅减少。 学习曲线:需要理解闭包、依赖数组、渲染时序等新心智模型。
逻辑复用:自定义 Hook 复用状态逻辑,避免 HOC 嵌套。 依赖数组易错:useEffect/useMemo/useCallback 的依赖数组写漏会导致 bug(闭包过期值)。
相关逻辑聚合:订阅/更新/清理写在一起,可读性高。 规则约束:只能在顶层调用、只能从函数组件调用,用错会报错或行为诡异。
易于测试:函数组件纯逻辑更易用单元测试覆盖。 过度调用:useMemo/useCallback 滥用反而造成额外开销和代码噪音。
利于性能优化:配合 React.memo 精准控制重渲染。 与第三方 class 组件混用:部分老库仍用 class,需要额外适配。

客观看待:Hooks 不是"银弹"。对简单展示组件,函数组件直接写就行,不必强行拆出一堆 Hook。优点和缺点往往是一体两面——灵活即风险,需要在实践中权衡。


4. 如何使用 Hook:两条铁律

Hook 的使用有两条不可违反的规则。违反它们不会直接报错,但会导致状态错乱、逻辑丢失等极难排查的 bug。

规则一:只在顶层调用 Hook 不要在循环、条件判断(if)、嵌套函数里调用 Hook。Hook 必须始终在组件函数的最顶层、以相同顺序被调用。因为 React 靠"调用顺序"来关联每个 Hook 与它的状态,顺序变了,状态就对不上号。

规则二:只在 React 函数组件或自定义 Hook 中调用 不要从普通 JavaScript 函数里调用 Hook。要么在函数组件里,要么在另一个自定义 Hook(名字以 use 开头)里。

用一个"反例"说明规则一的危害:

错误示范:条件里调用 Hook

function BadComponent({ show }: { show: boolean }) {
  if (show) {
    const [data, setData] = useState<string | null>(null); // 条件分支里调用 Hook
  }
  const [other, setOther] = useState<number>(0);   // 顺序不稳定
  return <View />;
}

正确示范:无条件、固定顺序

function GoodComponent({ show }: { show: boolean }) {
  // 所有 Hook 都在顶层、无条件调用
  const [data, setData] = useState<string | null>(null);
  const [other, setOther] = useState<number>(0);

  // 需要用 "show" 做逻辑时,放到 effect 内部判断
  useEffect(() => {
    if (show) {
      // 拉取数据的副作用
    }
  }, [show]);

  return <View />;
}

让工具帮你守住规则:安装 eslint-plugin-react-hooks 并开启 rules-of-hooks 和 exhaustive-deps 规则,ESLint 会在你违规时直接给出提示。新建的 RN 项目(npx react-native init)通常已默认开启。

关于"依赖数组"

useEffect、useMemo、useCallback 都接受一个"依赖数组"参数,用于声明这个 Hook 依赖了哪些变量。规则:凡是在回调内部用到的外部变量,都应该写进依赖数组,否则会读到过期(stale)的值。ESLint 的 exhaustive-deps 会自动检查这一点。


5. 常用 Hooks 详解(附可运行示例)

下面是 React Native 开发中最常用的 Hook。每个都配有可直接运行的完整组件示例——把代码复制进你的 RN 项目(函数组件放在 App.js 或任一屏组件中即可运行)。

Hook 用途
useState 状态管理
useEffect 副作用 / 生命周期
useContext 跨组件共享数据
useReducer 复杂状态逻辑
useMemo 缓存计算结果
useCallback 缓存函数引用
useRef 可变引用 / 节点
useLayoutEffect 渲染前同步副作用
useWindowDimensions RN 屏幕尺寸(RN 专属)
useColorScheme RN 主题模式(RN 专属)
useSafeAreaInsets 安全区(社区)
自定义 Hook 逻辑复用

5.1 useState —— 状态管理

useState 让函数组件拥有状态。返回一个二元数组:[状态值, 更新函数]。

import React, { useState } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';

interface Profile {
  name: string;
  age: number;
}

export default function CounterScreen() {
  // 基本用法:初始值 0
  const [count, setCount] = useState<number>(0);

  // 初始值来自函数(惰性初始化,只在首次渲染执行一次)
  const [timestamp, setTimestamp] = useState<number>(() => Date.now());

  // 也可以存对象、数组
  const [profile, setProfile] = useState<Profile>({ name: '小明', age: 18 });

  return (
    <View style={styles.container}>
      <Text style={styles.count}>计数:{count}</Text>
      <Text style={styles.sub}>首次渲染时间:{timestamp}</Text>
      <Text style={styles.sub}>姓名:{profile.name},年龄:{profile.age}</Text>

      <Pressable
        style={styles.btn}
        onPress={() => {
          // 函数式更新:基于上一次的值计算,避免闭包过期
          setCount((c: number) => c + 1);
          // 更新对象时注意展开旧对象,否则会丢字段
          setProfile((p: Profile) => ({ ...p, age: p.age + 1 }));
        }}
      >
        <Text style={styles.btnText}>+1</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff' },
  count: { fontSize: 40, fontWeight: '700' },
  sub: { fontSize: 16, marginTop: 8, color: '#555' },
  btn: { marginTop: 24, backgroundColor: '#0e7490', paddingHorizontal: 40, paddingVertical: 12, borderRadius: 8 },
  btnText: { color: '#fff', fontSize: 18 },
});

要点 - 更新状态用函数式更新(setCount(c => c + 1)),尤其在连续多次更新、或在 effect 内更新时,能避免读到旧值。 - 状态是不可变的:更新对象/数组要生成新引用(用展开运算符 ... 或新数组),不能直接修改原对象。 - 对象里多个字段可以合并成一个 state,也可以拆成多个 state,按可读性选择。


5.2 useEffect —— 副作用 / 生命周期

useEffect 用于处理副作用:数据请求、订阅、定时器、日志、操作原生模块等。它在渲染之后执行,并可以返回一个"清理函数"。

它覆盖了 class 组件里 componentDidMount、componentDidUpdate、componentWillUnmount 三个生命周期的大部分场景。

import React, { useState, useEffect } from 'react';
import { View, Text, Pressable } from 'react-native';

export default function EffectScreen() {
  const [count, setCount] = useState<number>(0);
  const [online, setOnline] = useState<boolean>(true);

  // 场景 1:空依赖 [] —— 只在挂载时执行一次(相当于 componentDidMount)
  // 返回的清理函数在卸载时执行(相当于 componentWillUnmount)
  useEffect(() => {
    const timer = setInterval(() => {
      console.log('心跳 tick');
    }, 5000);

    return () => {
      clearInterval(timer); // 组件卸载时清理,防止内存泄漏
      console.log('组件卸载,定时器已清理');
    };
  }, []);

  // 场景 2:带依赖 [count] —— 挂载时 + count 每次变化时执行
  useEffect(() => {
    console.log(`count 变化了:${count}`);
  }, [count]);

  // 场景 3:无依赖数组 —— 每次渲染后都执行(尽量少用)
  useEffect(() => {
    console.log('每次都执行');
  });

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff' }}>
      <Text style={{ fontSize: 32 }}>count: {count}</Text>
      <Text style={{ fontSize: 16, color: '#555', marginTop: 8 }}>网络状态:{online ? '在线' : '离线'}</Text>
      <Pressable
        style={{ marginTop: 24, backgroundColor: '#0e7490', padding: 14, borderRadius: 8 }}
        onPress={() => setCount((c: number) => c + 1)}
      >
        <Text style={{ color: '#fff' }}>count +1(触发依赖 effect)</Text>
      </Pressable>
    </View>
  );
}

一个常见陷阱:闭包过期值 如果 effect 的回调里用到了外部变量,但没写进依赖数组,它读到的永远是"那次渲染时"的旧值。例如上面的场景 2 若不写 [count] 而只写 [],那么回调里始终看到的是 count 的初始值 0。

要点 - 用依赖数组控制执行时机:[] 挂载一次;[a, b] 依赖变化时;不传则每次渲染。 - 需要清理的副作用(定时器、订阅、监听器)一定要返回清理函数,避免内存泄漏。 - 数据请求建议放在 [] 或带参数的 effect 里,并处理"组件已卸载"的竞态(可用一个标志位或用 AbortController)。


5.3 useContext —— 跨组件共享数据

useContext 让你读取一个 Context(上下文)里的值,避免层层传递 props(prop-drilling)。在 React Native 里常用于共享主题、用户登录信息、语言、设置等全局数据。

它需要配合 createContext 使用:先用 createContext 创建,再用 Provider 包裹要共享数据的组件树,最后在任意子组件里用 useContext 读取。

import React, { createContext, useContext, useState } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';

// 定义 Context 值的类型
interface ThemeContextValue {
  mode: 'light' | 'dark';
  toggle: () => void;
}

// 1. 创建 Context,并给出默认值
const ThemeContext = createContext<ThemeContextValue>({
  mode: 'light',
  toggle: () => {},
});

// 2. 提供一个 Provider 组件,管理并下发状态
function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [mode, setMode] = useState<'light' | 'dark'>('light');
  const toggle = () => setMode((m) => (m === 'light' ? 'dark' : 'light'));

  return (
    <ThemeContext.Provider value={{ mode, toggle }}>
      {children}
    </ThemeContext.Provider>
  );
}

// 3. 任意深度的子组件都可以直接读取,无需逐层传 props
function Header() {
  const { mode, toggle } = useContext(ThemeContext);
  const isDark = mode === 'dark';

  return (
    <View style={[styles.header, isDark && styles.darkHeader]}>
      <Text style={[styles.title, isDark && styles.darkText]}>主题:{mode}</Text>
      <Pressable
        style={[styles.btn, isDark && styles.darkBtn]}
        onPress={toggle}
      >
        <Text style={[styles.btnText, isDark && styles.darkText]}>切换主题</Text>
      </Pressable>
    </View>
  );
}

export default function App() {
  return (
    <ThemeProvider>
      <Header />
    </ThemeProvider>
  );
}

const styles = StyleSheet.create({
  header: { padding: 24, alignItems: 'center' },
  darkHeader: { backgroundColor: '#1f2933' },
  title: { fontSize: 22, fontWeight: '700', marginBottom: 16 },
  darkText: { color: '#e6edf3' },
  btn: { backgroundColor: '#0e7490', paddingHorizontal: 28, paddingVertical: 10, borderRadius: 8 },
  darkBtn: { backgroundColor: '#155e75' },
  btnText: { color: '#fff', fontSize: 16 },
});

要点 - Provider 的 value 变化时,所有 useContext 读取该 Context 的组件都会重渲染。想避免不必要的重渲染,可将 value 用 useMemo 缓存。 - Context 适合"低频变化的全局数据"。高频变化的数据(如实时输入)会让整棵子树频繁重渲染,这时考虑更局部的状态。 - 在 RN 中,主题切换是最典型的使用场景,常与 useColorScheme(下文)结合。


5.4 useReducer —— 复杂状态逻辑

当状态更新逻辑复杂、或一个状态受多个动作影响时,useReducer 比 useState 更清晰。它接收一个 reducer 函数和初始状态,返回 [state, dispatch]。你通过 dispatch({ type: 'xxx', payload }) 派发动作,reducer 根据动作返回新状态。

它的思想与 Redux 一致,但内置在 React 里,无需额外依赖。

import React, { useReducer } from 'react';
import { View, Text, TextInput, Pressable, StyleSheet, Alert } from 'react-native';

// 定义状态与动作类型
interface FormState {
  name: string;
  age: string;
  errors: { name?: string; age?: string };
}

type Action =
  | { type: 'SET_FIELD'; field: 'name' | 'age'; value: string }
  | { type: 'VALIDATE' }
  | { type: 'RESET' };

// 初始状态
const initialState: FormState = { name: '', age: '', errors: {} };

// reducer:根据 action.type 返回新状态(必须是纯函数)
function reducer(state: FormState, action: Action): FormState {
  switch (action.type) {
    case 'SET_FIELD':
      return { ...state, [action.field]: action.value, errors: { ...state.errors, [action.field]: undefined } };
    case 'VALIDATE': {
      const errors: FormState['errors'] = {};
      if (!state.name.trim()) errors.name = '姓名不能为空';
      const age = parseInt(state.age, 10);
      if (!state.age || isNaN(age) || age < 0 || age > 150) errors.age = '请输入有效年龄';
      return { ...state, errors };
    }
    case 'RESET':
      return initialState;
    default:
      return state;
  }
}

export default function FormScreen() {
  const [state, dispatch] = useReducer(reducer, initialState);

  const handleSubmit = () => {
    dispatch({ type: 'VALIDATE' });
    // 由于 dispatch 是异步的,这里用一个同步校验来判断
    const hasError = !state.name.trim() || isNaN(parseInt(state.age, 10));
    if (hasError) {
      Alert.alert('校验失败', '请修正错误后再提交');
    } else {
      Alert.alert('成功', `提交了 ${state.name},${state.age} 岁`);
      dispatch({ type: 'RESET' });
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>姓名</Text>
      <TextInput
        style={styles.input}
        value={state.name}
        onChangeText={(v: string) => dispatch({ type: 'SET_FIELD', field: 'name', value: v })}
        placeholder="输入姓名"
      />
      {state.errors.name && <Text style={styles.err}>{state.errors.name}</Text>}

      <Text style={styles.label}>年龄</Text>
      <TextInput
        style={styles.input}
        value={state.age}
        keyboardType="numeric"
        onChangeText={(v: string) => dispatch({ type: 'SET_FIELD', field: 'age', value: v })}
        placeholder="输入年龄"
      />
      {state.errors.age && <Text style={styles.err}>{state.errors.age}</Text>}

      <Pressable style={styles.btn} onPress={handleSubmit}>
        <Text style={styles.btnText}>提交</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 24, backgroundColor: '#fff' },
  label: { fontSize: 16, fontWeight: '600', marginTop: 12 },
  input: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 12, marginTop: 6, fontSize: 16 },
  err: { color: '#b91c1c', marginTop: 4, fontSize: 13 },
  btn: { backgroundColor: '#0e7490', borderRadius: 8, padding: 14, alignItems: 'center', marginTop: 24 },
  btnText: { color: '#fff', fontSize: 16, fontWeight: '600' },
});

useState vs useReducer - 简单、独立的状态用 useState。 - 状态之间有关联、更新逻辑复杂、或需要多种动作时用 useReducer。 - reducer 必须是纯函数:不要在里面做请求、修改外部变量,只根据 (state, action) 返回新状态。


5.5 useMemo —— 缓存计算结果

useMemo 缓存一个计算结果。它接收一个"计算函数"和依赖数组,只有当依赖变化时才重新计算,否则复用上一次的结果。适合"计算开销较大、且依赖不常变"的场景。

import React, { useMemo, useState } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';

function expensiveCompute(items: number[]): number {
  // 模拟一个很慢的统计:对数组做大量遍历求和
  console.log('正在执行耗时计算...');
  let sum = 0;
  for (const n of items) {
    sum += n * n;
  }
  return sum;
}

export default function MemoScreen() {
  const [items, setItems] = useState<number[]>([1, 2, 3, 4, 5]);
  const [tick, setTick] = useState<number>(0);

  // 只有当 items 变化时才重新计算;tick 变化不会触发重算
  const result = useMemo(() => expensiveCompute(items), [items]);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>平方和:{result}</Text>
      <Text style={styles.sub}>tick:{tick}(点击它不会触发耗时计算)</Text>
      <Pressable
        style={styles.btn}
        onPress={() => setTick((t: number) => t + 1)}
      >
        <Text style={styles.btnText}>仅改 tick</Text>
      </Pressable>
      <Pressable
        style={[styles.btn, styles.btn2]}
        onPress={() => setItems((arr: number[]) => [...arr, Math.ceil(Math.random() * 10)])}
      >
        <Text style={styles.btnText}>新增一项(触发重算)</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff' },
  title: { fontSize: 26, fontWeight: '700' },
  sub: { fontSize: 14, color: '#555', marginTop: 8 },
  btn: { marginTop: 16, backgroundColor: '#0e7490', paddingHorizontal: 24, paddingVertical: 10, borderRadius: 8 },
  btn2: { backgroundColor: '#155e75' },
  btnText: { color: '#fff', fontSize: 15 },
});

别滥用:useMemo 本身有内存开销,且会让代码更难读。只有当计算确实昂贵、且依赖不常变时才有收益。简单的加法、拼字符串、数组 length 等,直接算即可,不要包 useMemo。


5.6 useCallback —— 缓存函数引用

useCallback 缓存一个函数引用,只有当依赖变化时才创建新函数。它本身不缓存计算结果,目的是让"传给子组件的函数"引用稳定,从而配合 React.memo 避免子组件无意义地重渲染。

import React, { useState, useCallback, memo } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';

interface ListItemProps {
  label: string;
  onPress: (label: string) => void;
}

// 用 memo 包裹的子组件:只有当 props 变化时才重渲染
const ListItem = memo(function ListItem({ label, onPress }: ListItemProps) {
  console.log(`ListItem 渲染了:${label}`);
  return (
    <Pressable style={styles.item} onPress={() => onPress(label)}>
      <Text>{label}</Text>
    </Pressable>
  );
});

export default function CallbackScreen() {
  const [items, setItems] = useState<string[]>(['苹果', '香蕉', '橙子']);

  // 用 useCallback:只要 items 不变,handlePress 的引用就保持不变
  const handlePress = useCallback((label: string) => {
    console.log('点击了:', label);
  }, []); // 空依赖:该函数内部没用到会变化的变量

  return (
    <View style={styles.container}>
      {items.map((it) => (
        <ListItem key={it} label={it} onPress={handlePress} />
      ))}
      <Pressable style={styles.btn} onPress={() => setItems((arr: string[]) => [...arr, '葡萄'])}>
        <Text style={styles.btnText}>新增一项</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 24, backgroundColor: '#fff' },
  item: { backgroundColor: '#eef1f5', padding: 14, borderRadius: 8, marginBottom: 8 },
  btn: { backgroundColor: '#0e7490', borderRadius: 8, padding: 14, alignItems: 'center', marginTop: 8 },
  btnText: { color: '#fff', fontSize: 16 },
});

要点 - useCallback 的真正价值在于配合 React.memo。如果子组件没有用 memo 包裹,那缓存函数引用意义不大。 - 依赖数组同样重要:如果回调里用到了外部变量,一定要写进依赖,否则会读到过期值。 - 别把每个函数都包 useCallback——它本身也有开销。只有当函数会作为 props 传给"被 memo 的子组件"、或进入 effect 的依赖时才有必要。


5.7 useRef —— 可变引用 / 节点

useRef 返回一个可变的 ref 对象,其 .current 属性可以保存任意值。它有两大用途:引用 DOM/原生节点,以及在多次渲染间保留可变值(不会触发重渲染)。

import React, { useRef, useState } from 'react';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';

export default function RefScreen() {
  // 用途 1:引用输入框节点,直接调用其方法
  const inputRef = useRef<TextInput>(null);

  // 用途 2:在渲染间保留一个可变计数器,但改变它不会触发重渲染
  const renderCount = useRef<number>(0);
  renderCount.current += 1;

  // 对比:真正的状态(变化会触发重渲染)
  const [text, setText] = useState<string>('');

  const focusInput = () => {
    inputRef.current?.focus(); // 通过 ref 让输入框聚焦
  };

  return (
    <View style={styles.container}>
      <Text style={styles.count}>已渲染次数(ref,不触发重渲染):{renderCount.current}</Text>
      <TextInput
        ref={inputRef}
        style={styles.input}
        value={text}
        onChangeText={setText}
        placeholder="输入内容"
      />
      <Pressable style={styles.btn} onPress={focusInput}>
        <Text style={styles.btnText}>聚焦输入框</Text>
      </Pressable>
      <Text style={styles.text}>你输入了:{text}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 24, backgroundColor: '#fff' },
  count: { fontSize: 14, color: '#555', marginBottom: 12 },
  input: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 12, fontSize: 16 },
  btn: { backgroundColor: '#0e7490', borderRadius: 8, padding: 14, alignItems: 'center', marginTop: 12 },
  btnText: { color: '#fff', fontSize: 16 },
  text: { fontSize: 16, marginTop: 12 },
});

useRef vs useState - useState 变化 → 触发重新渲染。 - useRef 的 .current 变化 → 不触发重新渲染。 - 需要"改了 UI 要跟着变"用 useState;需要"存个值但不想引起渲染"(如计时器 ID、前一次的 props、DOM 引用)用 useRef。

另一个常用技巧:用 useRef 保存"上一次的值",在 effect 里对比是否变化。


5.8 useLayoutEffect —— 渲染前同步副作用

useLayoutEffect 与 useEffect 签名完全一样,唯一的区别是执行时机:它在浏览器/DOM 完成布局之前同步执行,而 useEffect 在布局之后异步执行。

在 React Native 中,它会在 native 更新提交前同步运行,常用于需要"先测量再渲染"的场景(如根据内容高度调整布局)。应谨慎使用,因为同步执行会阻塞渲染,用多了会卡顿。

import React, { useState, useLayoutEffect, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default function LayoutEffectScreen() {
  const [height, setHeight] = useState<number>(0);
  const [size, setSize] = useState<number>(0);

  // useLayoutEffect:在提交更新前同步执行,适合先测量尺寸再定布局
  useLayoutEffect(() => {
    setHeight((h: number) => h + 10); // 注意:这里会导致二次渲染,仅作演示
  }, []);

  // useEffect:渲染完成后异步执行
  useEffect(() => {
    setSize(99);
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>useLayoutEffect 设置的 height:{height}</Text>
      <Text style={styles.sub}>useEffect 设置的 size:{size}</Text>
      <Text style={styles.note}>
        实际开发中,useLayoutEffect 多用于"测量某个 View 的尺寸后,用它来决定另一个 View 的布局",避免肉眼可见的闪烁。
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff', padding: 24 },
  title: { fontSize: 20, fontWeight: '700' },
  sub: { fontSize: 18, marginTop: 8 },
  note: { fontSize: 14, color: '#555', marginTop: 20, textAlign: 'center' },
});

要点 - 绝大多数情况用 useEffect 就够了。 - 只有当副作用"必须在布局完成前、且不能让用户看到中间态"(例如先测量再布局,避免闪烁)时才用 useLayoutEffect。 - 在服务端渲染(SSR)场景要避免用 useLayoutEffect(会警告),RN 中没有 SSR 则无此顾虑。


5.9 自定义 Hook —— 逻辑复用

把一段可复用的逻辑抽成一个以 use 开头的函数,就是自定义 Hook。它是 Hooks 组合的产物,也是"状态逻辑复用"的核心手段。

import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

interface UseFetchResult {
  data: Todo | null;
  loading: boolean;
  error: string | null;
  reload: () => Promise<void>;
}

// 自定义 Hook:网络请求 + loading + 错误状态
function useFetch(url: string): UseFetchResult {
  const [data, setData] = useState<Todo | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(url);
      const json = (await res.json()) as Todo;
      setData(json);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setLoading(false);
    }
  }, [url]);

  useEffect(() => {
    load();
    // 组件卸载后避免 setState 的竞态
    let active = true;
    return () => { active = false; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [load]);

  return { data, loading, error, reload: load };
}

// 另一个自定义 Hook:布尔状态切换
function useToggle(initial = false): [boolean, () => void] {
  const [value, setValue] = useState<boolean>(initial);
  const toggle = useCallback(() => setValue((v: boolean) => !v), []);
  return [value, toggle];
}

export default function CustomHookScreen() {
  const [visible, toggleVisible] = useToggle(false); // 复用 useToggle
  const { data, loading, error, reload } = useFetch(
    'https://jsonplaceholder.typicode.com/todos/1'
  );

  return (
    <View style={styles.container}>
      <Text style={styles.title}>useToggle:{visible ? '开' : '关'}</Text>
      <Pressable style={styles.btn} onPress={toggleVisible}>
        <Text style={styles.btnText}>切换</Text>
      </Pressable>

      {loading && <Text style={styles.text}>加载中...</Text>}
      {error && <Text style={[styles.text, { color: '#b91c1c' }]}>出错:{error}</Text>}
      {data && <Text style={styles.text}>标题:{data.title}</Text>}
      <Pressable style={[styles.btn, styles.btn2]} onPress={reload}>
        <Text style={styles.btnText}>重新加载</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 24, backgroundColor: '#fff' },
  title: { fontSize: 20, fontWeight: '700', marginBottom: 12 },
  text: { fontSize: 15, marginTop: 12 },
  btn: { backgroundColor: '#0e7490', borderRadius: 8, padding: 12, alignItems: 'center', marginTop: 8 },
  btn2: { backgroundColor: '#155e75' },
  btnText: { color: '#fff', fontSize: 15 },
});

要点 - 自定义 Hook 必须以 use 开头,这样 React 才能正确识别并应用 Hooks 规则。 - 可以在自定义 Hook 里组合任意核心 Hook,也能调用其他自定义 Hook。 - 这是 RN 中复用"键盘监听、网络状态、主题、权限、设备信息"等逻辑的标准做法。


5.10 RN 专属 / 社区常用 Hooks

除了核心 Hook,React Native 自带几个与设备相关的 Hook,社区库也提供了一批高频 Hook。

useWindowDimensions —— 屏幕尺寸(RN 自带)

实时获取屏幕宽高,屏幕尺寸变化(旋转、分屏)时自动更新并触发重渲染。

import React from 'react';
import { View, Text, useWindowDimensions, StyleSheet } from 'react-native';

export default function WindowScreen() {
  const { width, height, scale, fontScale } = useWindowDimensions();

  const isLandscape = width > height;

  return (
    <View style={styles.container}>
      <Text style={styles.title}>屏幕信息</Text>
      <Text>宽:{width} · 高:{height}</Text>
      <Text>像素密度 scale:{scale} · 字体缩放:{fontScale}</Text>
      <Text style={styles.mode}>{isLandscape ? '横屏' : '竖屏'}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff' },
  title: { fontSize: 22, fontWeight: '700', marginBottom: 12 },
  mode: { fontSize: 18, marginTop: 12, color: '#0e7490', fontWeight: '700' },
});

useColorScheme —— 系统主题模式(RN 自带)

获取系统当前是"浅色"还是"深色"模式,并随系统设置自动更新。

import React from 'react';
import { View, Text, useColorScheme, StyleSheet } from 'react-native';

export default function ColorSchemeScreen() {
  const scheme = useColorScheme(); // 'light' | 'dark' | null
  const isDark = scheme === 'dark';

  return (
    <View style={[styles.container, isDark && styles.dark]}>
      <Text style={[styles.title, isDark && styles.darkText]}>
        当前系统主题:{scheme || '未知'}
      </Text>
      <Text style={[styles.sub, isDark && styles.darkText]}>
        试试在系统设置里切换深浅色模式,这里会跟着变。
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff' },
  dark: { backgroundColor: '#111' },
  title: { fontSize: 22, fontWeight: '700', marginBottom: 12 },
  sub: { fontSize: 15, color: '#555', textAlign: 'center', paddingHorizontal: 24 },
  darkText: { color: '#e6edf3' },
});

useSafeAreaInsets —— 安全区(社区 react-native-safe-area-context)

在 iPhone 刘海屏 / 全面屏上获取顶部、底部安全区距离,避免内容被遮挡。

// 先安装:npm install react-native-safe-area-context
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context';

function Content() {
  const insets = useSafeAreaInsets();
  return (
    <View style={[styles.container, { paddingTop: insets.top, paddingBottom: insets.bottom }]}>
      <Text style={styles.title}>安全区示例</Text>
      <Text>顶部安全区:{insets.top} · 底部:{insets.bottom}</Text>
      <Text>左右:{insets.left} / {insets.right}</Text>
    </View>
  );
}

export default function App() {
  return (
    <SafeAreaProvider>
      <Content />
    </SafeAreaProvider>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' },
  title: { fontSize: 22, fontWeight: '700', marginBottom: 12 },
});

6. 完整可运行 Demo

把下面这段合并成一个 App.js,在全新 RN 项目里运行,你就能在一个页面里看到多个 Hook 协同工作的效果:计数器(useState)、生命周期(useEffect)、耗时计算缓存(useMemo)、聚焦输入框(useRef)。

import React, { useState, useEffect, useMemo, useRef } from 'react';
import { View, Text, TextInput, Pressable, StyleSheet, SafeAreaView } from 'react-native';

export default function App() {
  const [count, setCount] = useState<number>(0);
  const [text, setText] = useState<string>('');
  const inputRef = useRef<TextInput>(null);

  // useEffect:挂载时启动定时器,卸载时清理
  useEffect(() => {
    const id = setInterval(() => console.log('App 存活中'), 5000);
    return () => clearInterval(id);
  }, []);

  // useMemo:缓存一个派生计算
  const bigNumber = useMemo(() => {
    let sum = 0;
    for (let i = 0; i < 100000; i++) sum += i;
    return sum + count;
  }, [count]);

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.title}>Hooks 综合 Demo</Text>

      {/* useState + 函数式更新 */}
      <Text style={styles.big}>计数:{count}</Text>
      <Pressable style={styles.btn} onPress={() => setCount((c: number) => c + 1)}>
        <Text style={styles.btnText}>+1</Text>
      </Pressable>

      {/* useMemo 结果 */}
      <Text style={styles.info}>useMemo 计算结果:{bigNumber}</Text>

      {/* useRef 聚焦 */}
      <TextInput ref={inputRef} style={styles.input} value={text} onChangeText={setText} placeholder="输入点东西" />
      <Pressable style={[styles.btn, styles.btn2]} onPress={() => inputRef.current?.focus()}>
        <Text style={styles.btnText}>聚焦输入框</Text>
      </Pressable>
      <Text style={styles.info}>你输入了:{text}</Text>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 24, backgroundColor: '#fff' },
  title: { fontSize: 26, fontWeight: '800', marginBottom: 20 },
  big: { fontSize: 36, fontWeight: '700', marginVertical: 12 },
  info: { fontSize: 15, color: '#555', marginVertical: 10 },
  btn: { backgroundColor: '#0e7490', borderRadius: 8, padding: 14, alignItems: 'center' },
  btn2: { backgroundColor: '#155e75', marginTop: 10 },
  btnText: { color: '#fff', fontSize: 16, fontWeight: '600' },
  input: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 12, fontSize: 16, marginTop: 14 },
});

7. 最佳实践

把前文要点汇总成一份可照做的清单。

7.1 遵守两条铁律

  • 只在顶层、无条件调用 Hook。
  • 只在函数组件或自定义 Hook 中调用。
  • 用 eslint-plugin-react-hooks 自动守护(rules-of-hooks + exhaustive-deps)。

7.2 正确使用依赖数组

  • effect / memo / callback 内部用到的外部变量,一律写进依赖数组。
  • 想"只跑一次"就用 [],但先确认回调里没有依赖外部可变值。
  • 依赖变化导致 effect 重复执行时,先想清楚是"依赖写多了"还是"逻辑该拆"。

7.3 用函数式更新,保持状态不可变

  • 连续更新或 effect 内更新用 setX((v) => ...)。
  • 对象/数组更新永远生成新引用({...} / [...]),绝不原地修改。

7.4 合理使用 useMemo / useCallback,别滥用

  • 只有计算昂贵、或函数要传给"被 memo 的子组件"时再用。
  • 过早优化是万恶之源:先用 React.memo + 实际性能数据说话,再决定缓存什么。

7.5 抽自定义 Hook 复用逻辑

  • 任何"跨组件可复用的状态逻辑"都应抽成 useXxx。
  • 命名以 use 开头,单一职责,内部封装好 loading / error / 清理。

7.6 副作用一定要清理

  • 定时器、订阅、监听器、请求,凡有清理需求的,在 effect 里返回清理函数。
  • 处理"组件卸载后 setState"的竞态(标志位 / AbortController)。

7.7 区分 useState / useRef / useReducer

  • 要"驱动 UI 变化" → useState。
  • 只想"存值但不触发渲染"或"引用节点" → useRef。
  • 状态逻辑复杂、动作多样 → useReducer。

7.8 区分 useEffect / useLayoutEffect

  • 默认用 useEffect。
  • 必须在布局前同步完成、且不能有可见中间态时才用 useLayoutEffect(会阻塞渲染,慎用)。

7.9 关注渲染性能

  • 大列表用 FlatList / SectionList,不要用 map 渲染所有项。
  • 用 React.memo 包裹"props 不常变"的子组件,配合 useCallback 稳定回调引用。
  • Context value 用 useMemo 缓存,避免子树频繁重渲染。

7.10 保持组件小而专注

  • 一个组件只做一件事,避免"巨型组件 + 一堆 Hook"。
  • 展示型组件与逻辑型自定义 Hook 分离,便于测试与复用。

结语

Hooks 是 React Native 开发的基石。掌握 useState / useEffect 就能写出一半的业务代码;再加上 useMemo / useCallback / useRef 处理性能与引用,useContext / useReducer 管理跨组件与复杂状态,再配合自定义 Hook 做逻辑复用,你就能写出简洁、可维护、高性能的 RN 应用。

把每一节的示例代码跑一遍,理解"为什么"而不只是"怎么写",你对 Hooks 的理解就会越过"会用"到达"用对"。