Basic understanding of react hooks (functional components)

Keywords: Javascript Front-end React

When using React, functional components have no state, so they were called stateless components at that time. What is hook?   Hook is a special function that allows you to "hook in" the React feature. When using hooks, you can hook in other functions so that functional components can achieve the effect of components defined by class.

1,useState()

useState() can return an array containing a data and a function. The data is equivalent to the data in the state defined by the class component, and the function is equivalent to setState(), which is used to modify the data state.

import { useState } from "react";

function Demo() {

  // Declare a state variable called "count"
  // The value passed in by useState() is the initial value of count
  // Another way to write:
  // const data = setCount(0)
  // const count = data[0]
  // const setCount = data[1]
  const [count, setCount]= useState(0) 
  return (
    <div>
      <h2>The data is:{count}</h2>
      // Use setCount() to change the state of count
      <button onClick={() => {setCount(count + 1)}}>click me</button>
    </div>
  )
}

If we want to use multiple state variables, it allows us to give different names to different state variables.

2,useEffect()

Effect Hook   It allows you to perform side effects in function components,   Can put   useEffect   Hook as   componentDidMount,componentDidUpdate   and   componentWillUnmount   A combination of these three functions.

import { useEffect, useState } from "react";

export default function Effect() {
  // Declare the variable count first
  const [count, setCount] = useState(0)
  // When you click change count, the contents in the function will be executed
  useEffect(() => {
    console.log('The component is hanging----', count);
    
  })
  
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => {setCount(count + 1)}}>click me</button>
    </div>
  )
}
import { useEffect, useState } from "react";
import { Routes, Route, Link } from 'react-router-dom'

// Component I
function Demo1() {
  useEffect(() => {
    console.log('demo1 Mounted---');
    // Use the function returned by return to listen for the destruction of components
    return () => {
      console.log('demo1 Destroyed');
    }
  })
  return (
    <>
      <h1>This is demo1</h1>
    </>
  )
}

// Component II
function Demo2() {
  useEffect(() => {
    console.log('demo2 Mounted---');
  })
  return (
    <>
      <h1>This is demo2</h1>
    </>
  )
}

// Component III
function Index() {
  useEffect(() => {
    console.log('Index Mounted---');
  })
  return (
    <>
      <h1>This is Index</h1>
    </>
  )
}

export default function Effect() {
  const [count, setCount] = useState(0)
  useEffect(() => {
    console.log('The component is hanging----');
    
  },[]) // Add [], so that the function will not continue to execute with the change of count. You can also use, [count] to listen for the change of count
  
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => {setCount(count + 1)}}>click me</button>
      <ul>
        {/* Link route, showing the destruction of components */}
        <li><Link to="/demo1">go demo1</Link></li>
        <li><Link to="/demo2">go demo2</Link></li>
        <li><Link to="/">default</Link></li>
      </ul>
      {/* Configure routing rules */}
      <Routes>
        <Route path="/demo1" element={<Demo1 />}></Route>
        <Route path="/demo2" element={<Demo2 />}></Route>
        <Route path="/" element={<Index />}></Route>
      </Routes>
    </div>
  )
}

2,createContext(), useContext(), useReducer()

Using createContext(), you can return a component object to provide usage:  

import {createContext, useState} from 'react'
export const colorContext = createContext()

export const UPDATE_COLOR = "UPDATE_COLOR"

// Use the color component to wrap the components that need the variable color. The children received by the props parameter, that is, those components of the package, are then rendered to receive the values on both sides of the passed value.
export const Color = props => {
  const [color, setColor] = useState('red')
  return (
    <div>
      <colorContext.Provider value={{color}}>
        {props.children}
      </colorContext.Provider>
    </div>
  )
}

useContext() is used by components that need data. useContext() passes in createContext() and returns a component object. So as to get the value passed by value.

Receive a context object (createContext())   And returns the current value of the context. The current context value is determined by the value closest to the current component in the upper component  < MyContext.Provider>   of   value   prop decision.

It can realize the direct transfer of grandson component data.

When the upper layer of the component is the nearest  < MyContext.provider>   When updated, the Hook triggers re rendering and uses the latest data passed to the   MyContext   provider's context   value   Value.

// Introduce the object returned by createContext()
import { colorContext } from "./color"
import { useContext } from "react"

export default function ContextDemo() {
  const {color} = useContext(colorContext)

  return (
    <div>
      <h1 style={{color}}>Font color is</h1>
    </div>
  )
}

useReducer(), pass in two parameters. The first is a function and the second is an initial value,   useState   Alternatives. It receives a shape such as   (state, action) => newState   reducer for

reducer:

// State is the previous state value, and the initial value is the second parameter value passed in using useReducer
// action is an object that contains behavior and state
const reducer = (state, action) => {
  switch (action.type) {
    case UPDATE_COLOR:
      return action.color
    default:
      return state
  }
}

When used, it returns the current state and its supporting   dispatch   method. use   dispatch   Pass an action object,

Contains a type attribute and the status value you want to return.

import { useReducer} from "react"


export default function ReduceDemo() {
  const [color, dispatch] = useReducer(reducer, 'red')
  
  return (

    <div>
      <button onClick={() => {dispatch({type: 'UPDATE_COLOR', color: 'deeppink'})}}>Pink</button>
      <button onClick={() => {dispatch({type: 'UPDATE_COLOR', color: 'green'})}}>green</button>
    </div>
  )
}

const reducer = (state, action) => {
  switch (action.type) {
    case UPDATE_COLOR:
      console.log(state)
      return action.color
    default:
      console.log(state)
  }
}

The combination of the three can replace redux.

4,useMemo()

When the child component obtains data from the parent component, when other data of the parent component is updated, it will also cause re rendering of the child component, which will consume performance.

Using useMemo can avoid.

function Blue({blue}) {

  function changeBlue(blue) {

    console.log('Blue updated ');

    return blue

  }

  const nBlue = useMemo(() => changeBlue(blue), [blue])

  return (

    <>

      <h1>{nBlue}</h1>

    </>

  )

}

Posted by bitman on Sun, 28 Nov 2021 04:21:28 -0800