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 MySQL select optimization solution

Table of contents Examples from real life Slow qu...

JavaScript jigsaw puzzle game

This article example shares the specific code of ...

Two implementation solutions for vuex data persistence

Table of contents Business requirements: Solution...

Implementation example of scan code payment in vue project (with demo)

Table of contents Demand background Thought Analy...

jQuery custom magnifying glass effect

This article example shares the specific code of ...

JS implements request dispatcher

Table of contents Abstraction and reuse Serial Se...

MySQL Order By Multi-Field Sorting Rules Code Example

Say it in advance On a whim, I want to know what ...

Mini Program Custom TabBar Component Encapsulation

This article example shares the specific code for...

Detailed explanation of using Vue custom tree control

This article shares with you how to use the Vue c...

Reasons why MySQL 8.0 statistics are inaccurate

Preface Whether it is Oracle or MySQL, the new fe...