React Hooks
React Hooks is an important feature introduced in React 16.8. It enables function components to have some features of class components, such as state management and the use of lifecycle methods.
With Hooks, you can write React components more concisely and flexibly.
1. What are React Hooks?
React Hooks is an enhancement mechanism for function components that allows you to use React features without writing class components. The main Hooks includeuseState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, anduseImperativeHandleetc. These Hooks provide a way to access React features, allowing you to better organize and reuse your code.
2. Main React Hooks
useState
useStateThe Hook allows you to use local state in function components. It returns a state value and a function to update that state value.
Example
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
useEffect
useEffectThe Hook allows you to perform side-effect operations in function components (such as data fetching, subscription management, DOM operations, etc.). It executes after every render.
Example
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []); // An empty array as the second parameter means it only runs when the component mounts and unmounts
return <p>Timer: {seconds} seconds</p>;
}
The following are some main React Hooks and their uses:
useState - Used to add state in function components; you can use it to track data that changes over time.
const [state, setState] = useState(initialState);
useEffect- Used to perform side-effect operations, such as data fetching, subscriptions, or manually changing the DOM. It is similar to the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components.
useEffect(() => {
// 执行副作用操作
return () => {
// 清理操作
};
}, [dependencies]); // 依赖数组useContext- Used to access data passed through React context in the component tree, without having to pass props through every component.
const value = useContext(MyContext);
useReducer- Used for more complex state logic. It takes a reducer function and an initial state, then returns the current state and a dispatch function for dispatching actions.
const [state, dispatch] = useReducer(reducer, initialState);
useCallback- Used to return a memoized version of a callback function to prevent unnecessary renders.
const memoizedCallback = useCallback(
() => {
// 回调函数体
},
[dependencies] // 依赖数组
);useMemo- Used to memoize calculation results, avoiding repeated calculations on every render.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
useRef- Used to create references to DOM elements or values, which can maintain state between renders.
const refContainer = useRef(initialValue);
useImperativeHandle- Used to expose DOM element methods when using refs.
useImperativeHandle(ref, () => ({
// 暴露的方法
}));
useLayoutEffect - 与 useEffect 类似,但它在所有的 DOM 变更之后同步执行。这在需要读取 DOM 布局并同步触发重渲染时非常有用。
useLayoutEffect(() => {
// 副作用操作
}, [dependencies]);useDebugValue- Used to display a label for custom hooks in the React Developer Tools.
useDebugValue(value);
3. Benefits of Using React Hooks
- More concise component logic: No need to write class components; you can use function components and Hooks to manage state and lifecycle.
- Improved code reusability: Hooks can help you extract logic into reusable functions, reducing duplicate code.
- Better performance optimization: Use
useEffect,useCallback,useMemoand other Hooks to more precisely control side effects and performance costs.
4. Notes
- Only use Hooks at the top level: Do not call Hooks in loops, conditions, or nested functions. Ensure that Hooks are called in the same order on every render.
- Use the ESLint plugin: React officially provides the eslint-plugin-react-hooks plugin to help you check whether Hooks are used correctly.
5. Example
The following is an example that uses multiple React Hooks:
Example
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Update the title only when count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Example;
In the above code, we used useState to manage the count state, useEffect to update the page title, and a simple button to increase count.
With Hooks, you can write cleaner and more reusable component code.
Hooks also make testing component logic easier, because you can test the logic of each hook individually without wrapping it in a component.
In addition, Hooks support customization. You can write your own Hooks to encapsulate complex logic and then reuse them across multiple components.
Other Extensions