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

A brief discussion on browser compatibility issues in JavaScript

Browser compatibility is the most important part ...

MySQL 5.7.18 Green Edition Download and Installation Tutorial

This article records the detailed process of down...

MySQL example of getting today and yesterday's 0:00 timestamp

As shown below: Yesterday: UNIX_TIMESTAMP(CAST(SY...

SQL implementation of LeetCode (177. Nth highest salary)

[LeetCode] 177.Nth Highest Salary Write a SQL que...

ElementUI implements cascading selector

This article example shares the specific code of ...

Implementation of pushing Docker images to Docker Hub

After the image is built successfully, it can be ...

CSS controls the spacing between words through the letter-spacing property

letter-spacing property : Increase or decrease th...

Introduction to Nginx log management

Nginx log description Through access logs, you ca...

How to install openjdk in docker and run the jar package

Download image docker pull openjdk Creating a Dat...

Web design tips on form input boxes

This article lists some tips and codes about form...

The pitfall record of the rubber rebound effect of iOS WeChat H5 page

Business requirements One of the projects I have ...

How to change the root user's password in MySQL

Method 1: Use the SET PASSWORD command mysql> ...

HTTP and HTTP Collaboration Web Server Access Flow Diagram

A web server can build multiple web sites with in...

Use iframe to display weather effects on web pages

CSS: Copy code The code is as follows: *{margin:0;...