Use of React function components (Hooks)

Table of Contents

Hooks concept understanding

1. What are hooks?

2. What problems do Hooks solve?

useState

1. Basic usage

2. Reading and modifying status

3. Component update process

4. Rules of use

useEffect

1. Understand function side effects

2. Basic usage

3. Dependencies control execution timing

4. Clean up side effects


Hooks concept understanding

Tasks in this section: Be able to understand the concept of hooks and the problems they solve

1. What are hooks

The essence of Hooks: A set of “hooks” that can make functional components more powerful and flexible

Components in the React system are divided into class components and function components

After years of practice, function components are a component expression that is more in line with React’s design concept UI = f(data) and is more conducive to logical splitting and reuse. The previous function components were not It can have its own state. In order to allow function components to have their own state, Hooks came into being starting from react v16.8.

Points to note:

  1. With hooks, in order to be compatible with older versions, the class component has not been removed, and both can be used.

  2. With hooks, you can no longer turn functions into stateless components, because hooks provide state for function components.

  3. Hooks can only be used in function components

2. What problem does Hooks solve

The emergence of Hooks solves two problems: 1. State logic reuse of components 2. Problems with class components themselves

  1. Logic reuse of components Before hooks appeared, React successively tried mixins, HOC high-order components, render-props and other modes, but they all had their own problems, such as unclear data sources of mixins, nesting problems of high-order components, etc. wait

  2. Problems with the class component itself. The class component is like a heavy ‘battleship’. It is large and comprehensive and provides a lot of things. There is a learning cost that cannot be ignored, such as various life cycles, this pointing problems, etc., and we often What is needed is a light and flexible ‘speed boat’

useState

1. Basic usage

Tasks in this section: Be able to learn the basic usage of useState

Function

useState provides state for function components

Steps to use

  1. Import the useState function

  2. Call the useState function and pass in the initial value of the state

  3. Get the state and modify the state from the return value of the useState function

  4. Display status in JSX

  5. Call the method that modifies the status to update the status

Code implementation

import { useState } from 'react'
 ?
 function App() {
   // Parameter: initial value of the state. For example, passing in 0 means that the initial value of the state is 0.
   // Return value: array, containing two values: 1 state value (state) 2 function to modify the state (setState)
   const [count, setCount] = useState(0)
   return (
     <button onClick={() => { setCount(count + 1) }}>{count}</button>
   )
 }
 export default App

2. Reading and modifying status

Tasks in this section: Be able to understand the reading and modification of status under useState

Read status

The status provided by this method is a local variable inside the function and can be used anywhere within the function.

Edit status

  1. setCount is a function, and the parameters represent the latest status value

  2. After calling this function, the old value will be replaced with the new value

  3. After modifying the status, the view will change due to the status change.

Notes

  1. When modifying the state, you must replace the old state with the new state. You cannot directly modify the old state, especially the reference type.

const [count,setCount]=useState(0)

  1. The parameter passed by useSate is used as the initial value of count

  2. [count, setCount] The writing method here is a destructuring assignment. The return value of useState is an array.

    Can the name be customized? -> Can be customized to maintain semantics

    Can the order be changed? -> No. The first parameter is the data status. The second parameter is the method of modifying the data.

  3. The setCount function is used to modify count. It still cannot modify the original value or generates a new value to replace the original value.

    setCount (new value calculated based on the original value)

  4. count and setCount are a pair and are tied together. setCount can only modify the corresponding count value.

3. Component update process

Tasks in this section: Be able to understand the update of components after using hooks

The execution process of function components after using useState hook, and the changes in state values

  • Component is rendered for the first time

    1. Execute the code logic in the component from scratch

    2. Call useState(0) to use the passed parameters as the initial state value, that is: 0

    3. Render the component. At this time, the obtained status count value is: 0

  • Component renders for the second time

    1. Click the button and call setCount(count + 1) to modify the state. Because the state changes, the component will be re-rendered.

    2. When the component is re-rendered, the code logic in the component will be executed again.

    3. Call useState(0) again. At this time, React will internally get the latest state value instead of the initial value. For example, the latest state value in this case is 1

    4. Render the component again. At this time, the obtained status count value is: 1

Note: The initial value (parameter) of useState will only take effect when the component is rendered for the first time. In other words, for every subsequent rendering, useState will obtain the latest state value, and the React component will remember the latest state value each time.

 import { useState } from 'react'
 ?
 function App() {
   const [count, setCount] = useState(0)
   //You can perform printing tests here
   console.log(count)
   return (
     <button onClick={() => { setCount(count + 1) }}>{count}</button>
   )
 }
 export default App

4. Usage Rules

Tasks in this section: Be able to remember the usage rules of useState

  1. useState The function can be executed multiple times, each execution is independent of each other, and each call provides a state for the function component

  2. useState Notes

    • Can only appear in function components or other hook functions

    • Cannot be nested in if/for/other functions (react recognizes each hook in the order in which the hooks are called)

      let num = 1
       function List(){
         num++
         if(num / 2 === 0){
            const [name, setName] = useState('cp')
         }
         const [list,setList] = useState([])
       }
       // The order of the two hooks is not fixed, this is not allowed! ! ! 
    • You can check hooks status through developer tools

useEffect

1. Understand function side effects

Tasks for this section: Be able to understand the concept of side effects

What are side effects

Side effects are relative to the main effect. In addition to the main effect of a function, other effects are side effects. For React components, the main function is to render UI based on data (state/props), and other than that are side effects (for example, manually modifying the DOM)

Common side effects

  1. Data request ajax sent

  2. Manually modify dom

  3. localstorage operation

The function of useEffect function is to provide side effect processing for react function components!

2. Basic usage

Tasks in this section: Be able to learn the basic usage of useEffect and master the default execution timing

Function

Provide side effect handling for react function components

Steps to use

  1. Import the useEffect function

  2. Call the useEffect function and pass in the callback function

  3. Write side effect processing (dom operations) in the callback function

  4. Modify data status

  5. Check if side effects are taking effect

Code implementation

import { useEffect, useState } from 'react'
 ?
 function App() {
   const [count, setCount] = useState(0)
  
   useEffect(()=>{
     //dom operation
     document.title = `Currently clicked ${count} times`
   })
   return (
     <button onClick={() => { setCount(count + 1) }}>{count}</button>
   )
 }
 ?
 export default App

3. Dependencies control execution timing

Tasks in this section: Be able to learn to use dependencies to control the execution timing of side effects

1. Do not add dependencies

The component is executed once for the first rendering, and will be executed again no matter which state change causes the component to be updated.

  1. Component initial rendering

  2. Component updates (no matter which state causes the update)

 useEffect(()=>{
     console.log('Side effect executed')
 })

2. Add an empty array

The component is only executed once when it is first rendered

useEffect(()=>{
      console.log('Side effect executed')
 },[])
3. Add specific
<strong>Dependencies</strong>

Side-effect functions are executed on first render and re-executed when dependencies change

function App() {
     const [count, setCount] = useState(0)
     const [name, setName] = useState('zs')
     
     useEffect(() => {
         console.log('Side effect executed')
     }, [count])
     
     return (
         <>
          <button onClick={() => { setCount(count + 1) }}>{count}</button>
          <button onClick={() => { setName('cp') }}>{name}</button>
         </>
     )
 }

Notes

The data (for example, count) used in the useEffect callback function is dependency data and should appear in the dependency array. If dependencies are not added, bugs will occur.

4. Clean up side effects

If you want to clean up side effects, you can return a new function at the end of the side effect function and write the logic to clean up the side effects in the new function.

Note that the execution timing is:

  1. Automatically executed when component is uninstalled

  2. When the component is updated, it is automatically executed before the next useEffect side effect function is executed.

import { useEffect, useState } from "react"
 ?
 ?
 const App = () => {
   const [count, setCount] = useState(0)
   useEffect(() => {
     const timerId = setInterval(() => {
       setCount(count + 1)
     }, 1000)
     return () => {
       // Things to clean up side effects
       clearInterval(timerId)
     }
   }, [count])
   return (
     <div>
       {count}
     </div>
   )
 }
 ?
 export default App