react hooks如何用
React Hooks 的基本用法
React Hooks 是 React 16.8 引入的特性,允许在函数组件中使用状态和其他 React 特性。以下是常用 Hooks 的用法:
useState
用于在函数组件中添加局部状态。接受一个初始状态值,返回当前状态和一个更新状态的函数。
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
useEffect
用于在函数组件中执行副作用操作(如数据获取、订阅或手动修改 DOM)。可以替代生命周期方法 componentDidMount、componentDidUpdate 和 componentWillUnmount。
import React, { useState, useEffect } from 'react';
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // 空依赖数组表示只在组件挂载时执行
}
useContext
用于在函数组件中访问 React 的 Context,避免多级组件传递 props。

import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>Click me</button>;
}
useReducer
用于管理复杂的状态逻辑,类似于 Redux 的 reducer 模式。
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}
useRef
用于创建可变的 ref 对象,其 .current 属性被初始化为传入的参数。常用于访问 DOM 节点或保存可变值。

import React, { useRef } from 'react';
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
自定义 Hook
可以创建自定义 Hook 来复用状态逻辑。自定义 Hook 是一个函数,其名称以 "use" 开头,可以调用其他 Hook。
import { useState, useEffect } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
function MyComponent() {
const width = useWindowWidth();
return <div>Window width: {width}</div>;
}
Hooks 使用规则
只在 React 函数组件或自定义 Hook 中调用 Hooks。不要在循环、条件或嵌套函数中调用 Hooks。React 依赖 Hook 的调用顺序来正确保留状态。
性能优化
useMemo 用于记忆计算结果,避免每次渲染都重新计算。useCallback 用于记忆回调函数,避免子组件不必要的重新渲染。
import React, { useMemo, useCallback } from 'react';
function ExpensiveComponent({ list }) {
const sortedList = useMemo(() => {
return list.sort((a, b) => a - b);
}, [list]);
const handleClick = useCallback(() => {
console.log('Item clicked');
}, []);
return (
<ul>
{sortedList.map(item => (
<li key={item} onClick={handleClick}>{item}</li>
))}
</ul>
);
}
以上是 React Hooks 的基本用法和常见模式。Hooks 提供了一种更简洁和灵活的方式来编写 React 组件,使代码更易于理解和维护。






