What is the Hook
Hook is 16.8 React from the beginning supported features, use Hook can use state when not in use class
Hook support multiplexing logic state without the need to modify the status of the components used to solve complex and render prop higher order components generated code Structure
Hook can be solved in the class as a function of the life cycle of components within the dispersion caused by the processing logic confusion.
Hook can solve complex problems in class in this.
Hook structure
State Hook
When state management through the state, we will use the contructor () constructor to initialize the state, using setState () to update the status of state
In Hook, the above two methods are no longer used, will be used
const [name,setName]=useState(defaultValue);
Such a method of state management.
UseState will be called to add the state as a function of the component, a useState method will return a pair of values (an array), a function of the current status and update current status, you can call the update function elsewhere in the assembly.
This uses an array of deconstruction of the return value.
A useState statement will create a state.
Effect Hook
We can useEffect seen as componentDidMount, and componentWillUnmount componentDidUpdate combination of these three functions.
useEffect second optional parameter is determined whether to execute the function, if the second parameter is not changed when rendering heavy, will skip the current useEffect.
If the second parameter is an empty array ([]), will be performed only when Effect mount and unmount assembly, however there is a risk of such operation, see document specific Hook / the FAQ : dependency list function is omitted Is it safe?
A simple example
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// 相当于 componentDidMount 和 componentDidUpdate:
useEffect(() => {
// 使用浏览器的 API 更新页面标题
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In this example, declare a state called count, each time the button click event handler will by the count + 1, in useEffect function, use the browser's API will count display.