This is the 15th day of my participation in Gwen Challenge

Difference between a class component and a function component

  1. We can access the properties, methods, state, and props of the class component by using this.
  2. Class Components Components have their own life cycle, such as componentDidMount, componentWillUnmount, etc.
  3. Function components have no internal this and no life cycle of their own.

State Hook

This example is used to display a counter. When you click the button, the counter increases in value:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={()= > setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Copy the code

In this case, useState is a Hook (we’ll get to what that means in a moment). Add some internal state to the component by calling it from within the function component. React will retain this state for repeated rendering. UseState returns a pair of values: the current state and a function that lets you update it, which you can call in an event handler or some other place. It is similar to the this.setState of the class component, but it does not merge the new state with the old state.

Effect Hook

You’ve probably done fetch, subscribe, or manually modify the DOM in the React component before. We collectively refer to these operations as “side effects,” or simply “effects.”

UseEffect is an Effect Hook that gives function components the ability to manipulate side effects. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in the Class component, but has been consolidated into an API. (we’ll show examples of how to compare useEffect with these methods in using Effect Hook.)

For example, the following component sets a page title when React updates the DOM:

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  ComponentDidMount and componentDidUpdate:
  useEffect(() = > {
    // Update the page title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={()= > setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Copy the code

When you call useEffect, you’re telling React to run your “side effect” function after making changes to the DOM. Because side functions are declared inside the component, they can access the props and state of the component. By default, React calls side effects after every render — including the first one. (We’ll compare this to the class component lifecycle method in more detail using Effect Hook.)

Side effects functions can also specify how to “clear” side effects by returning a function. For example, use the side effects function in the following component to subscribe to a friend’s online status and clear it by unsubscribing:

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  useEffect(() = > {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () = > {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading... ';
  }
  return isOnline ? 'Online' : 'Offline';
}
Copy the code

useState hook

If we want to define the state of a component when using a class component, we can declare the state of the component directly by defining state on the constructor or property of the component, as follows:

class A extends React.Component {
  constructor() {
    super(a);this.state = {
      count: 1}}}Copy the code

In the function component we need to define the state of the component. How do we do that? We need to use our useState method to define the state of the function component:

const App = () = > {
   const [count,setCount] = useState(0);
   return (
     <button onClick={()= >{setCount (count + 1)}} > PM me</button>)}Copy the code

This defines a state in the function component.

useContext hook

The hook is used to share state between components. Context can be used for state distribution, which is supported after react16.x. React avoids the need to pass data layer by layer through Props. Here is an example. Now assume that there are components A and B that need to share A state.

import React,{ useContext } from 'react'
const AppContext = React.createContext({})
 
const A =() = > {
    const { name } = useContext(AppContext)
    return (
        <p>I am the name of component A {name}<span>I am A child of A {name}</span></p>)}const B =() = > {
  const { name } = useContext(AppContext)
  return (
      <p>I am the name of component B {name}</p>)}const Ceshi = () = > {
  return (
    <AppContext.Provider value={{name: 'hookTest '}} >
	  <A/>
	  <B/>
    </AppContext.Provider>)}export default Ceshi
Copy the code

As you can see, we can share state using hooks.

useRef hook

In the class component we want to save a value. We can store the value on the property of the class component, but in the function component since we don’t have this, we can store the value in the useRef:

import React, { useRef, useEffct } from 'react';
const Test = () = > {
 const divRef = useRef();
 const countRef = useRef(0);
 useEffect(() = > {
    console.log(divRef.current)
 }, [])
  return (
     <div ref={divRef} onClick={()= >{countref.current+ +}}> I'm a div</div>)}Copy the code

useCallback hook

In a class component we can use the class component property to declare an arrow function method to ensure that the props for calling this function do not change.

import React, { useCallback } from 'react';
const Test = () = > {
   const onClick = () = > {
      console.log('aaa')}return (
      <div onClick={onClick}>Am I</div>)}Copy the code

When the Test component is updated every time, the onClick function is a new arrow, which will be reflected as a div and will be updated every time.

import React, { useCallback } from 'react';
const Test = () = > {
   const onClick = useCallback(() = > {
      console.log('aaa')
   },[]);
   return (
      <div onClick={onClick}>Am I</div>)}Copy the code

With useCallback, useCallback stores functions, improving performance.

useMemo hook

For heavy computations, we can use useMemo for caching:

import React, { useCallback, useState } from 'react';
const Test = () = > {
  const [length,setLength] = useState(1);
   const data = useMemo(() = > {
       let str = ' '; 
       for(let i = 0; i< length; i++) {
		 str+='This is a string.'
       }
      return str;
   },[length]);
   
     
const onClick = useCallback(() = > {
      setLength(1000)
},[]);
   
   return (
      <div onClick={onClick}>The point I {data}</div>)}Copy the code

Hooks are used on two principles:

  • Do not use hooks for loops, conditional judgments, or function nesting
  • Use hooks only in function components