What is the method of using hooks in React?
The method of using Hooks in React is as follows:
- Import the necessary Hooks functions like useState, useEffect, etc. by using: import { useState, useEffect } from ‘react’;
- In a functional component, call a Hooks function by assigning it to a variable: const [state, setState] = useState(initialValue). Here, useState is a Hooks function that can be used to define a state variable and a function to update the state. initialValue is the initial value.
- You can use the state variable to access the current state value and the setState function to update the state value.
- You can use useEffect inside the body of a functional component to handle side effects, such as subscribing to data or manipulating the DOM. useEffect takes a callback function and an optional dependency array, with the callback function being executed after the component is rendered. The dependency array specifies that the callback function should only be re-executed when the dependencies in the array change.
Note: Hooks can only be called at the top level of a function component, not inside loops, conditional statements, or nested functions.
This is an example using Hooks.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
// 在组件渲染后执行
document.title = `You clicked ${count} times`;
}, [count]); // 仅在count发生变化时才会重新执行
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the example above, we used useState to define a state variable named count and an update function named setCount. Within useEffect, we used document.title to display information on the current click count, and passed [count] as a dependency so that the callback function will only be re-executed when the count changes.