React Hooks 核心:useState 与 useEffect 实践
Hooks 是 React 函数组件的主力 API。
1. useState
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>点击了 {count} 次</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
}2. useEffect
import { useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
return () => {
// 清理(取消订阅、清除定时器等)
};
}, [userId]); // 依赖数组
return <div>{user?.name}</div>;
}3. 自定义 Hook
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initial;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}Hooks 让函数组件功能完备,是 React 开发的主流方式。
