react中的hook如何使用
React Hook 的基本概念
Hook 是 React 16.8 引入的特性,允许在不编写 class 的情况下使用 state 和其他 React 特性。常见的 Hook 包括 useState、useEffect、useContext、useReducer 等。
useState 的使用
useState 用于在函数组件中添加局部 state。
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useState 返回一个数组,第一个元素是当前 state 值,第二个元素是更新 state 的函数。初始值通过参数传递。
useEffect 的使用
useEffect 用于处理副作用操作,如数据获取、订阅或手动修改 DOM。
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect 接受两个参数:第一个是副作用函数,第二个是依赖数组。依赖数组中的值变化时,副作用函数会重新执行。

useContext 的使用
useContext 用于在函数组件中访问 React 的 Context。
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme === 'dark' ? 'black' : 'white' }}>Themed Button</button>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}
useContext 接收一个 Context 对象并返回当前 Context 的值。
useReducer 的使用
useReducer 是 useState 的替代方案,适用于复杂 state 逻辑。

import React, { useReducer } from 'react';
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, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
useReducer 接收一个 reducer 函数和初始 state,返回当前 state 和 dispatch 函数。
自定义 Hook
自定义 Hook 可以将组件逻辑提取到可重用的函数中。
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
function App() {
const { data, loading } = useFetch('https://api.example.com/data');
if (loading) return <div>Loading...</div>;
return <div>{data}</div>;
}
自定义 Hook 必须以 use 开头命名,以便 React 识别其为 Hook。
Hook 的使用规则
- 只能在函数组件或自定义 Hook 中调用 Hook。
- 不能在循环、条件或嵌套函数中调用 Hook。
Hook 的设计使得 React 能够正确追踪 state 和副作用。






