React Hooks深入理解与实践
React Hooks自16.8版本引入以来,彻底改变了React组件的编写方式。它让函数组件拥有了状态管理和副作用处理的能力,同时提供了更优雅的逻辑复用方案。本文将深入探讨Hooks的原理和高级用法。
一、useState与useReducer
// useState - 基础状态管理
const [count, setCount] = useState(0);
// 函数式更新 - 基于前一个状态
setCount(function(prev) { return prev + 1; });
// 惰性初始化 - 避免每次渲染都执行昂贵计算
const [data, setData] = useState(function() {
return expensiveComputation(initialValue);
});
// useReducer - 复杂状态逻辑
function reducer(state, action) {
switch (action.type) {
case "increment": return { count: state.count + 1 };
case "decrement": return { count: state.count - 1 };
case "reset": return { count: action.payload };
default: return state;
}
}
const [state, dispatch] = useReducer(reducer, { count: 0 });
dispatch({ type: "increment" });
dispatch({ type: "reset", payload: 0 });
二、useEffect与副作用
// 基础用法
useEffect(function() {
var subscription = subscribe(channel);
return function() { subscription.unsubscribe(); };
}, [channel]);
// 常见模式:数据获取
function useUser(userId) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(function() {
var cancelled = false;
setLoading(true);
fetchUser(userId)
.then(function(data) { if (!cancelled) setUser(data); })
.catch(function(err) { if (!cancelled) setError(err); })
.finally(function() { if (!cancelled) setLoading(false); });
return function() { cancelled = true; };
}, [userId]);
return { user: user, loading: loading, error: error };
}
三、自定义Hook
// useDebounce - 防抖Hook
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(function() {
var timer = setTimeout(function() { setDebouncedValue(value); }, delay);
return function() { clearTimeout(timer); };
}, [value, delay]);
return debouncedValue;
}
// useLocalStorage - 持久化状态
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(function() {
try {
var item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
var setValue = function(value) {
var valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
};
return [storedValue, setValue];
}
四、性能优化Hooks
// useMemo - 缓存计算结果
const sortedItems = useMemo(
function() { return items.sort(function(a, b) { return a.name.localeCompare(b.name); }); },
[items]
);
// useCallback - 缓存函数引用
const handleClick = useCallback(
function(id) { selectItem(id); },
[selectItem]
);
// React.memo - 缓存组件渲染
var MemoizedList = React.memo(function List(props) {
return props.items.map(function(item) {
return React.createElement(Item, { key: item.id, data: item });
});
});
React Hooks让函数组件更加强大,但也需要理解其闭包陷阱和性能特征。掌握Hooks的核心原理和最佳实践,是成为React高级开发者的关键。