This is the 26th day of my participation in the August More Text Challenge

React Hooks are a set of hook functions that enhance functional components. React Hooks provide different functions. Hook functions start with use.

Provides state for function components

Internally, the useState function uses closures to store state data.

What is the return value of useState?

The return value is an array. The first item of the array is the state data, and the second item is the method to set the state data. For naming the second item, we usually use the set+ state data name method.

const [count,setCount] = useState(0);
Copy the code

The details of the useState

  1. Accepts a unique parameter, the state initializer, which can be of any data type.
  2. The return value is an array that stores the state value and the method to change the state value. The method name convention begins with set followed by the state name.
  3. Methods can be called multiple times to hold different state values.
  4. The argument can be a function, the initial state is whatever the function returns, and the function will only be called once, if the initial value is a dynamic value.
function App(props) {
    const [count,setCount] = useState(() = > {
        return props.count || 10;
    });
    const [person,setPerson] = useState({name: 'justin'})
    return (
        <div>
            <span>{count},{person.name}</span>
            <br />
            <button onClick={()= > setCount(count + 1)}>+1</button>
            <button onClick={()= >SetPerson ({name: 'country '})}> Click toggle name</button>
        </div>)}Copy the code

UseState updates the status asynchronously

function App(props) {
    const [count,setCount] = useState(0);
    const [person,setPerson] = useState({name: 'justin'})
    function handleCount() {
        setCount(() = > {
            return count + 1;
        })
        console.log(count);   // Prints 0, indicating asynchronous
    }
    return (
        <div>
            <span>{count},{person.name}</span>
            <br />
            <button onClick={handleCount}>+ 1</button>
            <button onClick={()= >SetPerson ({name: 'country '})}> Click toggle name</button>
        </div>)}Copy the code

Read the state

In class, you read state using this.state, but in hook, you just use the variable name of the state.

Why useState and not createState?

Since the word Create is not very accurate, since state is only created when the component is first rendered, useState returns the current state on the next rendering.