One, foreword

Hooks use state and other React features without writing a class. Learn what Hooks are, why they are used, what Hooks are commonly used in React, and how to customize them.

The learning materials for this article are mainly from the Official document React Hooks and Wang Pei’s column “Core Principles and Practice”.

What are Hooks

Hooks are the functions inside function components that hook in external functions.

React provides some common hooks. React also supports custom hooks that introduce external functionality to functions.

When we need to introduce external functionality in a component, we can use the React hooks or custom hooks.

For example, to introduce state-managing capabilities into a component, you can use the useState function, which is described in more detail below.

B. which are Hooks

Hooks are used for 2 big reasons:

  • Simplified logic reuse;
  • Make complex components easier to understand.

1. Simplify logic reuse

React had to borrow complex design patterns such as high-order components and render props to reuse logic before Hooks came along, but high-order components produced redundant component nodes, making debugging more complex.

Hooks let us reuse state logic without changing the component structure; the use of custom Hooks is described in more detail below.

2. Make complex components easier to understand

In a Class component, code for the same business logic is distributed among different lifecycle functions of the component. Hooks allow code for the same business logic to be grouped together, separating the business logic clearly and making the code easier to understand and maintain.

B. which is in the use of Hooks

1. useState

UseState is a Hook that allows you to add state to the React function component.

The following is an example:

import React, { useState } from 'react';

function Example() {
  // Declare a state variable called "count"
  const [count, setCount] = useState(0);
  // ...
Copy the code

The above code declares a state variable count with an initial value of 0, and updates the current count by calling setCount.

2. useEffect

UseEffect lets you perform side effects in function components.

A side effect is a piece of code that has nothing to do with the result of the current execution. Common side effects include fetching data, setting up subscriptions, and manually changing the DOM in the React component.

UseEffect can accept two arguments as follows:

useEffect(callback, dependencies)
Copy the code

The first argument is the function callback to execute, and the second argument is the optional dependency array Dependencies.

The dependency is optional; if not specified, the callback will be executed after each function component is executed. If specified, it is executed only when the value in the dependency changes.

The following is an example:

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 () = > {
        // Can be used for cleanup, equivalent to class component componentWillUnmount
    }

  }, [count]); // Specify the dependency count to perform the side effect when count is updated
  // ...
Copy the code

The above code uses useEffect to execute the side effect function when the dependency count is updated and to clear the last execution result by returning the callback function.

In addition, useEffect provides four times to perform side effects:

  • Execute after each render: no second dependency argument is provided. UseEffect (() => {});
  • Execute only after the first render: provide an empty array as a dependency. UseEffect (() => {}, []);
  • First time and after a dependency change: Provides an array of dependencies. UseEffect (() => {}, [deps]);
  • Component executed after unmount: Returns a callback function. UseEffect () => {return () => {}}, []).

3. useCallback

The callback defined by useCallback will only be redeclared when the dependency changes, ensuring that the component does not create duplicate callbacks. Components that receive this callback function as a property do not need to be rerendered frequently.

The following is an example:

const memoizedCallback = useCallback(() = > {
  doSomething(a, b)
}, [a, b])
Copy the code

The above code redeclares the callback function only when the dependencies A and B change.

4. useMemo

The creation function defined by useMemo is recalculated only when a dependency changes, helping to avoid costly computations with each rendering, and components that receive this calculated value as a property do not need to be rerendered frequently.

The following is an example:

const memoizedValue = useMemo(() = > computeExpensiveValue(a, b), [a, b])
Copy the code

The above code is recalculated only when dependencies A and B change.

5. useRef

UseRef returns a REF object that persists throughout the life of the component.

It serves two purposes:

  • Save references to DOM nodes;
  • Sharing data between multiple renders.

An example of the introduction of saving DOM nodes is as follows:

function TextInputWithFocusButton() {
  const inputEl = useRef(null)
  const onButtonClick = () = > {
    // 'current' points to the text input element mounted to the DOM
    inputEl.current.focus()
  }
  return (
    <>
      <input ref={inputEl} type='text' />
      <button onClick={onButtonClick}>Focus the input</button>
    </>)}Copy the code

The above code creates the ref object with useRef, holds a reference to the DOM node, and can do DOM manipulation on the ref.current.

An example of sharing data between multiple renders is as follows:

import React, { useState, useCallback, useRef } from 'react'

export default function Timer() {
  // Define time state to hold the cumulative time for timing
  const [time, setTime] = useState(0)

  // Define a container for holding a variable between component renderings
  const timer = useRef(null)

  // Start the timer event handler
  const handleStart = useCallback(() = > {
    // Use the current attribute to set the value of ref
    timer.current = window.setInterval(() = > {
      setTime((time) = > time + 1)},100)}, [])// Suspend the timer event handler
  const handlePause = useCallback(() = > {
    // Use clearInterval to stop the timer
    window.clearInterval(timer.current)
    timer.current = null
  }, [])

  return (
    <div>
      {time / 10} seconds.
      <br />
      <button onClick={handleStart}>Start</button>
      <button onClick={handlePause}>Pause</button>
    </div>)}Copy the code

The above code creates a ref object with the variable name timer from useRef, which can be called when rendering across components, creating a new timer when it starts and clearing it when it pauses.

6. useContext

UseContext is used to receive a context object and return the value of the context, enabling data sharing across hierarchies.

The following is an example:

// Create a context object
const MyContext = React.createContext(initialValue)
function App() {
  return (
    // Pass the value of Context through context.provider
    <MyContext.Provider value='1'>
      <Container />
    </MyContext.Provider>)}function Container() {
  return <Test />
}

function Test() {
  // Get the value of Context
  const theme = useContext(MyContext) / / 1
  return <div></div>
}
Copy the code

The above code uses useContext to get the Context defined in the App component to share data across the hierarchy of components.

7. useReducer

Using the useReducer, you can introduce the Reducer function.

The following is an example:

const [state, dispatch] = useReducer(reducer, initialState)
Copy the code

It takes the Reducer function and the initial value of the state as arguments and returns an array. The first member of the array is the current value of the state, and the second member is the dispatch function that sends the action.

Customize Hooks

With custom Hooks, component logic can be extracted into reusable functions.

1. How to create custom Hooks?

Custom Hooks are functions that have two characteristics that distinguish them from normal functions:

  • The name starts with “use”.
  • The function calls other hooks internally.

The following is an example:

import { useState, useCallback } from 'react'

function useCounter() {
  // Define the state of count to hold the current value
  const [count, setCount] = useState(0)
  // Add 1
  const increment = useCallback(() = > setCount(count + 1), [count])
  // subtract by 1
  const decrement = useCallback(() = > setCount(count - 1), [count])
  // Reset the counter
  const reset = useCallback(() = > setCount(0), [])

  // Export the operations of the business logic for use by the caller
  return { count, increment, decrement, reset }
}

1 / / component
function MyComponent1() {
  const { count, increment, decrement, reset } = useCounter()
}

2 / / component
function MyComponent2() {
  const { count, increment, decrement, reset } = useCounter()
}
Copy the code

Easily reuse business logic between MyComponent1 and MyComponent2 components using custom Hooks useCounter.

2. Customize react-use library

React provides the React-Use library, which contains a number of custom Hooks that can be used directly to simplify component logic and improve code readability and maintainability.

Where we use custom Hooks:

  • UseLocation and useSearchParam: Track the location of the navigation bar.
  • UseScroll: Tracks the scrolling position of HTML elements
  • UseScrolling: Tracks whether HTML elements are scrolling
  • UseAsync, useAsyncFn, and useAsyncRetry: resolves an async function;
  • UseTitle: Sets the page title.

Visit the react-Use website to learn how to use it.

Six, the summary

Remember that Reacterhooks are used by people who want to use them. Remember that reacterhooks are used by people who want to use them. Remember that reacterhooks are used by people who want to use them.

Hope you can help, thanks for reading ~

Don’t forget to point a praise to encourage me oh, pen core ❤️

The resources

  • React official document -Hook
  • React Hooks core principles and Practice
  • React Hooks tutorial
  • Easy to learn the React Hooks implementation principles
  • How do React Hooks implement it