Introduction to useRef and useState in JavaScript

Introduction to useRef and useState in JavaScript

1. useState hook

useState is a built-in React hook that allows you to store information as state in variables. It allows you to add React state to functional components. In the following example, useState() declares a state variable, and the value is stored in a count variable. setCount is the function used to update this value.

//Import useState from react

import React, { useState } from 'react';

function Count() {

  //Declare a new state variable called count const [count, setCount] = useState(0);

2. useRef hook

useRef hook is a built-in React hook that takes an argument or parameters as its initial value and returns a reference or persisted mutable value. This reference, or ref for short, contains a value that can be retrieved using the current property.

We can also store the user input in refs and display the collected data as follows:

//Import useRef hook

import React, { useRef } from "react"

export default function App() {

  //Create a variable to store the reference const nameRef = useRef();

  function handleSubmit(e) {

    //Prevent the page from reloading on submit e.preventDefault()

    // Output name

    console.log(nameRef.current.value)

  }

  return (

    <div className="container">

      <form onSubmit={handleSubmit}>

        <div className="input_group">

          <label>Name</label>

          <input type="text" ref={nameRef}/>

        </div>

        <input type="submit"/>

      </form>

    </div>

  )

}

3. useRef and useState

  • Unlike state, the data or value stored in a ref or reference remains unchanged, even after the component re-renders. Therefore, refs do not affect component rendering, but state does.
  • useState returns 2 properties or an array. One is the value or state, and the other is a function that updates the state. In contrast, useRef returns only one value, the actual stored data.
  • When the reference value changes, it updates without refreshing or re-rendering. But in useState , the component has to render again to update the state or its value.

4. When to use Refs and States

refs are useful for obtaining user input, DOM element attributes, and storing continuously updated values. However, if you want to store information about a component or use methods in your component, states are the best choice.

So in summary, these two hook have their own advantages and disadvantages, and will be used depending on the situation and purpose.

This is the end of this article about useRef and useState in JavaScript . For more information about useRef and useState in JavaScript , please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the new array methods in JavaScript es6
  • The connection between JavaScript and TypeScript
  • How to remove jsessionid after URL in Springboot
  • JS block-level scope and private variable example analysis
  • JavaScript uses closures to simulate block-level scope operations
  • In-depth understanding of the use of es6 block-level scope
  • ES6 learning tutorial: block-level scope detailed explanation
  • In-depth understanding of ES6 study notes: block-level scope binding
  • ES6 uses the let command to more easily implement block-level scope example analysis
  • JavaScript ES new feature block scope

<<:  The latest collection of 18 green style web design works

>>:  Detailed explanation of redo log and undo log in MySQL

Recommend

Detailed explanation of how to use the Vue license plate search component

A simple license plate input component (vue) for ...

CSS3 uses var() and calc() functions to achieve animation effects

Preview knowledge points. Animation Frames Backgr...

Thirty HTML coding guidelines for beginners

1. Always close HTML tags In the source code of p...

HTML table tag tutorial (34): row span attribute ROWSPAN

In a complex table structure, some cells span mul...

Vue two fields joint verification to achieve the password modification function

Table of contents 1. Introduction 2. Solution Imp...

CentOS 7.2 builds nginx web server to deploy uniapp project

Panther started as a rookie, and I am still a roo...

Web page HTML code explanation: ordered list and unordered list

In this section, we will learn about list element...

MySQL slow query pt-query-digest analysis of slow query log

1. Introduction pt-query-digest is a tool for ana...

How to use Samba to build a shared file service on a Linux server

Recently, our small team needs to share a shared ...

30 minutes to give you a comprehensive understanding of React Hooks

Table of contents Overview 1. useState 1.1 Three ...

Detailed explanation of Linux lsof command usage

lsof (list open files) is a tool to view files op...

MySQL log system detailed information sharing

Anyone who has worked on a large system knows tha...

7 ways to vertically center elements with CSS

【1】Know the width and height of the centered elem...