What are Hooks?

Hooks are functions that can “hook “React state and lifecycle features into function components. React 16.8 is a new feature. It lets you use state and other React features without having to write a class.

What it does: Provides functions to function components, such as state and life cycles, that are originally provided in Class components

Note:

  • Hooks can only be used in function components
  • Can be understood as hooking the class component’s features for the function component via Hooks

Comparison of component development patterns before and after Hooks

  • React V16.8 before: Class component (provides state) + function component (displays content)
  • React V16.8 and later:

(1) Class component (provide state) + function component (display content)

(2)Hooks(provide state) + function components (display content)

(3) Use a mix of Hooks+ functions and class components for some functions

Why Hooks

The essence of the React component

React is a JavaScript library for building user interfaces.

The React component encapsulates specific functions and is mainly used to split the UI.

The React component Model is a straightforward mapping from Model to View. The Model corresponds to the React function as state and props

Formula: Component (State+Props) = UI

Problems with the class component itself

The class component does not perform its most important function in rendering the UI by state:

  • Components rarely inherit from one another
  • Components rarely visit each other

Benefits of functional components

  • The function itself is simpler and better able to render the UI based on state
  • Hooks give function components the ability to maintain state internally
  • Hooks bring logical reuse capabilities to components

Use policy for hooks

React has no plans to remove classes from React

(2)Hook and existing code can work at the same time, you can use it gradually:

  • Large-scale refactoring of existing components directly using Hooks is not recommended
  • Hooks are recommended for new functions. If complex functions cannot be implemented, use class
  • Find a simple, non-core component and start using hooks

(3) Use the hooks API for the class component

  • The state and setState
  • Hook function,componentDidMount,componentDidUpdate,componentWillUnmount
  • thisRelated usage

(4) The original learning content needs to be used

  • JSX:{},onClick={handleClick}, conditional rendering, list rendering, style processing, etc
  • Component: function component, component communication
  • React development concept:Unidirectional data flow,State of ascension

UseState – Basic use

Usage scenarios

When you want to use component state in a function component, use the useState Hook.

Using the step

(1) Import useState function

(2) Call the useState function, pass in the initial value, return the state and modify the state function

(3) use

  • Displayed in JSXstate
  • Call the function that modifies the state at a specific time to change the state

Example:

import { useState } from 'react'
// useState is a hook, hook is a function starting with use
const Count = () = > {  
Const [state,setState] = useState(0
  // 0 is the initial value
  The return value is an array
  const stateArray = useState(0)
  // Status value -> 0
  const state = stateArray[0]
  // A function to modify the state
  const setState = stateArray[1]

  return (
    <div>{/* Display status values */}<h1>useState Hook -> {state}</h1>{/* Click the button to make the status value +1 */}<button onClick={()= > setState(state + 1)}>+1</button>
    </div>)}Copy the code
  • Parameter: initial status value. For example, passing a 0 indicates that the initial value of the state is 0

    (1) Note: The state here can be any value (for example, value, string, etc.), and the state in the class component must be an object

  • Return value: array, containing two values: 1 state value (state) 2 Function to modify the state (setState)

UseState – Handles form elements

  • Use useState to initialize content and modify content methods
  • Set the value and onChange attributes to the input element
import React, { useState } from 'react'
import ReactDom from 'react-dom'
export default function App () {
  const [content, setContent] = useState(' ')
  return (
    <div>
      {content}
      <input value={content} onChange={(e)= > setContent(e.target.value)} />
    </div>
  )
}
ReactDom.render(<App />.document.getElementById('root'))
Copy the code

Usestate-setxxx callback function format

UseState two formats

Format 1: Pass the value

useState(0) useState('abc')

Format 2: Incoming callback

UseState (() => {return initial value})

(1) The return value of the callback function is the current value of the state

(2) The callback function fires only once

Usage scenarios

Format 1: Pass the value

If the state is just plain data (for example, string, number, array, etc.) you can use useState directly (plain data)

Format 2: Incoming callback

The initial state takes some calculation. UseState (()=>{here is some calculation, return result}))

SetXXX can be a callback

States need to be accumulated iteratively. SetXXXXX ((last value) => {return new value})

Example:

import React, { useState } from 'react'
import ReactDom from 'react-dom'
export default function App () {
  const [count, setCount] = useState(0)
  const hClick1 = () = > {
    setCount(count+1)
    setCount(count+1)
    setCount(count+1)}const hClick2 = () = > {
    setCount((count) = > {
      return count + 1
    })
    setCount((count) = > {
      return count + 1
    })
    setCount((count) = > {
      return count + 1})}return (
    <div>
      count:{count}
      <button onClick={hClick1}>Multiple consecutive setCount- values</button>/ / 1<button onClick={hClick2}>Many consecutive</button>/ / 3</div>
  )
}
ReactDom.render(<App />.document.getElementById('root'))
Copy the code

UseState – Component update process

Example:

import { useState } from 'react'

const Count = () = > {  
  console.log('Count... ')
  const [count, setCount] = useState(0)
  return (
    <div>{/* Display status values */}<h1>useState Hook -> {count}</h1>{/* Click the button to make the status value +1 */}<button onClick={()= > setCount(count + 1)}>+1</button>
    </div>)}Copy the code

The update process

Use useState Hook to execute the function component and change the state value:

  • Component first render:

    (1) Execute the code in the function component

    (2) Call useState(0) with the parameter passed as the initial value of the state, namely: 0

    (3) Render component. At this point, the obtained state count value is 0

The user clicks the button and calls setCount(count + 1) to change the state. As the state changes, the component is re-rendered

  • Component second render:

    (1) Execute the code logic in this component again

    UseState (0) :

    React gets the latest state value instead of the initial value

    (4) The latest status value in this case is 1

    (5) Render the component again. At this point, the obtained state count value is: 1

The initial value (parameter) of useState only takes effect when the component is first rendered

const [count, setCount] = useState(() = >{
  console.log('useState... ') // This sentence will be output only once
  return 0
})
Copy the code

That is, useState gets the latest state value for each subsequent render. The React component remembers the latest state value each time!

The summary is as follows:

  • Status updates, and the logic of the entire component is rerun
  • UseState only uses the initial value of the state for the first rendering of the component, and then the latest value of the state
  • The useState Hook is used to manage state, which enables function components to maintain state. That is, the state is shared between multiple renders of a function component.

How do I provide multiple states for function components?

  • Plan 1:UseState ({state 1, state 2..... })
  • Scheme 2:UseState (State 1) useState(State 2)

Scheme 2 is recommended

You can call useState Hook several times, and each time you call useState Hook you can provide one state.

Note:

Hooks: setXXX(new value) ==> Replace previous value with new value

Class: setState({attribute to modify})

Rules for using useState

The rules

  • SeState can only appear directly inside a function component

  • UseState cannot be nested in if/for

    Reason: React identifies each Hook according to the sequence in which Hooks are called. If the sequence is different, React cannot know which Hook it is. You can view it through the developer tools

SeEffect side effects

Functional components:

  • Render UI based on data (state/props)
  • Side effects: Data (Ajax) requests, manual DOM modification, start timer, empty timer, add event listener, delete event, localStorage operation, etc

UseEffect – Basic use

Using the step

1. Import useEffect
import { useEffect } from 'react'

// 2. Use useEffect
useEffect(() = > {
	console.log('useEffect 1 executed, can do side effects')
})
useEffect(() = > {
	console.log('useEffect 2 executed, can do side effects')})Copy the code

Execution time

After the render job is done, Effect is executed;

If multiple definitions are specified, they are executed in sequence.

Example:

import React, { useState, useEffect } from 'react'
import ReactDom from 'react-dom'
export default function App () {
  useEffect(() = > {
    console.log('useEffect')
    document.title = 'count' + count
  })
  const [count, setCount] = useState(0)
  return (
    <div
      onClick={()= >{setCount(count + 1)}}> Function component {count}</div>
  )
}
ReactDom.render(<App />.document.getElementById('root'))
Copy the code

UseEffect dependencies

UseEffect takes two parameters:

Parameter 1: Side effect function.

Parameter 2: The dependency to execute the side effect function: It determines when to execute parameter 1 (side effect function)

UseEffect complete format

Case 1: No second argument. Timing: Execute after each update

Case 2: Takes a second argument, which is an empty array. Execution time: This parameter is executed for the first time

UseEffect () => {// the contents of the side effect function}, [])Copy the code

Usage scenario: 1 Event binding 2 Sending a request to obtain data.

Case 3: Takes a second argument (array format) and specifies a dependency. Execution time :(1) execute once initially. (2) execute once if the value of the dependency changes

UseEffect (() => {// Contents of the side effect function}, [dependency 1, dependency 2,....] )Copy the code

The dependency here is the state defined in the component.

Reference:

(1) useEffect complete Guide: Overreacted. IO/zh-Hans/A-C…