The Hook of the React

What is a Hook?

Hook is a new feature in React 16.8. It lets you use state and other React features (such as functional components) without writing a class.

A Hook is a function that lets you “Hook” features like React state and lifecycle into a function component. Hooks cannot be used in class components — this allows you to use React without using class.

Hook usage rules

Hooks are JavaScript functions, but there are two additional rules for using them:

  • onlyCall Hook in the outermost layer of the function. Do not call in loops, conditional judgments, or subfunctions.
  • onlyCall a Hook in the React function componentDo not call it in other JavaScript functions. (can also inCall a Hook in a custom Hook).

State Hook

UseState returns a pair of values: the current state and a function that lets you update it

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable called "count"
  const [count, setCount] = useState(0);
  const [todo, setTodo] = useState({dosomething: "aaa"});

  return (
    <div>
      <p>You clicked {count} times</p>
      <p>You clicked {todo.dosomething} times</p>
      <button onClick={()= > {
          setCount(count + 1);
          setTodo({dosomething: "bbb"})
      }}>
        Click me
      </button>
    </div>
  );
}
Copy the code

Effect Hook

UseEffect is an Effect Hook, which gives function components the ability to manipulate side effects (side effects). It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in the Class component, but has been consolidated into an API.

For example, the following component sets a page title when React updates the DOM:

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  ComponentDidMount and componentDidUpdate:
  UseEffect internal events are called for both component initial rendering and data update rendering
  useEffect(() = > {
    // Update the page title using the browser API
    document.title = `You clicked ${count} times`;
    
    alert("update"); // Count is executed every time it is updated
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={()= > setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Copy the code

The side effects function can also specify how to “clean” the side effects (to prevent memory leaks) by returning a function:

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() = > {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading... ';
  }
  return isOnline ? 'Online' : 'Offline';
}
Copy the code