This is the first day of my participation in Gwen Challenge

  • Hooks do not work inside a class.
  • When do you use hooks? When you write a component and need to add some state, not when you want to use a class component

useState

  • Returns a pair containing the current state and a function that updates it

const [count,setCount] =useState(0) //count is initially set to 0
Copy the code

useEffect

The basic use

  • Equivalent to componentDidMount and componentDidUpdate:
  • The first rendering of the page is complete, and the state changes are executed after the page is re-rendered (when the DOM update is complete)
useEffect(() = > {
    console.log('Count has changed')})Copy the code

UseEffect is triggered when state changes

  • Controlled when state is updated, but still triggered when the first render is complete
useEffect(() = > {
    console.log('Count has changed')
}, [count]) // The last argument is an array, specifying the state to listen on
Copy the code

unsubscribe

  useEffect(() = > {
    console.log('Count has changed')
    let timer = setInterval(() = > {
      console.log('Subscribed')},1000)
    // Returns a function to cancel some subscriptions when the component is destroyed
    return () = > {
      clearInterval(timer)
    }
  }, [age])

Copy the code

Multiple useEffect

  • If there are more than one useEffect, each useEffect will fire, so there is a question of firing order.

  • UseEffect is executed in the same order as its code is written,

  let [count, setCount] = useState(0)
  useEffect(function countEff() {  
    console.log('Count has changed')})let [age, setAge] = useState(1)
  useEffect(function ageEff() {
    console.log('Age has changed')})/ / output:
/ / count change
/ / the age changes
Copy the code

useContext

  • Used for multi-layer component value transfer, similar to vue privide/ Inject

  • For example

    • Ye components

      
      import React from 'react'
      const themes = {
        light: {
          foreground: "# 000000".background: "#eeeeee"
        },
        dark: {
          foreground: "#ffffff".background: "# 222222"}};const ThemeContext = React.createContext(themes.light);  // createContext Is created. The default value is optional
      function App() {
        return (
          <ThemeContext.Provider value={themes.dark}>// The value to be passed in via the value binding<Toolbar />
          </ThemeContext.Provider>
        );
      }
      Copy the code
    • The parent component

      function Toolbar(props) {
        return (
          <div>
            <ThemedButton />
          </div>
        );
      }
      Copy the code
    • Child components

      function ThemedButton() {
        const theme = useContext(ThemeContext); // Use useContext to receive incoming values
        return (
          <button style={{ background: theme.background.color: theme.foreground}} >
            I am styled by theme context!
          </button>
        );
      }
      Copy the code

useReducer

function ReducerDemo(){
    const [count,dispatch] =useReducer((state,action) = >{
        switch(action){
            case 'add': return state+1
            case 'sub': return state-1
            default :return state
        }
    },0)// Pass a reducer and an initial value
    return(
        <div>
            <h2>{count}</h2>
            <button onClick={()= >dispatch('add')}></button>
            <button onClick={()= >dispatch('sub')}></button>
        </div>)}Copy the code

UseCallback and useMemo

  • Caching functions to avoid repeated rendering
  • Usecallback monitors both a and B states and triggers doSomething in them when they change
const memoizedCallback = useCallback(
  () = > {
    doSomething(a, b);
  },
  [a, b],
);
Copy the code

useMemo

  • Similar to usecallback
const memoizedCallback = useMemo(
  () = > {
    doSomething(a, b);
  },
  [a, b],
);
Copy the code
  • Difference:

    • UseCallback is created without executing any of its functions

    • UseMemo is executed once when it is created (rendering the page)

      useCallback(() = >{}, deps) 
      / / equivalent to
      useMemo(() = > {
          // Return a function
          return () = >{}}, deps).Copy the code

Customize the hook


function useBodyScrollPosition() {
  const [scrollPosition, setScrollPosition] = useState(null);

  useEffect(() = > {
    const handleScroll = () = > setScrollPosition(window.scrollY);
    document.addEventListener('scroll', handleScroll);
    return () = >
      document.removeEventListener('scroll', handleScroll); } []);return scrollPosition;
}

Copy the code