A,Summary of Hooks

Hooks allow you to use more of React functionality without classes.

Features:

  • It’s totally opt-in. If you focus on class components, you don’t need to learn hooks. (For functional components only)
  • 100% backward compatibility.
  • Now available. (Official: class component concept will not be removed)

2. Use State Hook

Let’s start with a simple click count example:

(1) Implement useState using hooks

import { useState } from 'react';

function Example() {

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

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

(2) Using class components

class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button> </div> ); }}Copy the code

Conclusion:

In the class, we initialize count state to 0 by setting this.state to {count: 0} in the constructor;

But in functional components, we don’t have this, so we can’t assign or read this.state. So here we introduce the use of hooks to add state to functional components by calling useState directly from within the component.

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

We declare a state variable named count and set it to 0. React will remember its current value between re-renders and provide the latest value for our function. If we want to update the current count, we can call setCount.

UseState is a function that takes the initial value of the state variable and returns the current state and the function that updates it.

3. Use Effect Hook

First, know what a Side Effect is: A Side Effect is when a function or expression’s behavior depends on the outside world. Side effects are:

  • A function or expression modifies state outside its scope
  • In addition to returning statements, a function or expression has obvious interactions with the outside world or with the function it calls

What does Effect Hook do?

Effect Hook adds the ability to execute Side Effects to your functional components.
import { useState, useEffect } from 'react';

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

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

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

Here, we can think of useEffect Hook as a combination of componentDidMount, componentDidUpdate, and componentWillUnmount.

Here’s how to parse this code:

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
Copy the code

We declare the count state variable and tell React we need effect. We pass a function to the useEffect Hook, which is our effect. In our Effect, we used the Document.title browser API to set the document title. We can read the latest count in effect because it is in the scope of our function. When React renders our component, it remembers the effect we used and then runs our Effect after updating the DOM. This happens after every render, including the first.

B. use rules

  • Call hooks only at the top level. Do not call hooks in loops, conditions, or nested functions. Instead, always use Hooks at the top of the React function. By following this rule, you can ensure that the hooks are called in the same order every time a component is rendered. This is what allows React in multipleuseStateuseEffectWhy Hook state is properly preserved between calls.
  • ** Only use React Functions to call Hooks. ** Do not use in regular functions.

Note: We can use an esLint plugin called eslint-plugin-react-hooks that will enforce these two rules for us.