SoFunction
Updated on 2025-04-07

React Hooks' useState and useRef usage summary

React Hooks is a new feature introduced in React 16.8, which allows you to use state and other React features without writing class. in,useStateanduseRefThey are two commonly used Hooks.

1. useState

useStateis a Hook that allows you to add state to function components.

Instructions for use:

  • useStateReturns a state variable and a function that sets the variable.
  • If passed touseStateThe initial value isundefined, the initial value of the returned state variable isundefined
  • You can call anywhere in the componentuseState, but it is usually recommended to call it at the top level of the component.

Code example:

import React, { useState } from "react"
import { Button } from 'antd';
 
const IndexPage:  = () => {
  ("View Update");
  /**
    * The only parameter of useState is undefined when the initial state has no parameters.
    * useState() will return an array
    * Index 0 UseState passed in parameter
    * Index 1 Change the value of index 0 and refresh the view setObj is a method parameter is the value that needs to be changed.
    * We can assign values ​​to numbers or strings as needed, not necessarily objects
    **/
  const [obj, setObj] = useState({ count: 0 })
  const setCount = (obj: any) => {
    ++
    // When useState creates a variable of reference type, the memory address of setObj is the same as the memory address of obj. useState will not update the view.    // setObj(obj) // View will not be updated    setObj({ ...obj }) // The view will be updated    (obj);
  }
  return (
    <div>
      {}
      <br />
      <Button onClick={() => setCount(obj)}>count+1</Button>
    </div>
  );
}
 
export default IndexPage

2. useRef

useRefis an immutable (read-only) reference that can store any data type (such as a DOM element or a React component). ref is a responsive reference, which means that even if its call point has not changed, its pointing will be updated as the component renders.

Instructions for use:

  • useRefReturns a mutable ref object, which.currentThe attribute is initialized as the passed parameter (orundefined)。
  • .currentThe value of   remains unchanged throughout the life of the component.
  • The ref object remains unchanged throughout the life of the component.

Code example:

import React, { useRef } from "react"
import { Button } from 'antd';
 
const IndexPage:  = () => {
  // useRef() has a parameter as the initial value  const ref = useRef(1)
  (ref);
 
  return (
    <div ref={ref}>
    </div>
  );
}
 
export default IndexPage

This is the article about the useState and useRef usage summary of React Hooks. For more related React Hooks useState and useRef content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!