Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 8, 2022 05:40 pm GMT

React useRef Hook simple example

React useRef Hook

The useRef Hook is used to persist values between renders.
It does not cause a re-render when updated and can be used to store a mutable value, it also used to access a DOM element directly.

Below, is an example of useRef to keep the previous value of your state (name) after changing it.

import React, { useState, useEffect, useRef } from 'react';export default function App(){  const [name, setName] = useState('')  const prevName = useRef()  useEffect(()=> {    prevName.current = name  },[name])  return (     <>       <input value={name} onChange={e => setName(e.target.value)}/>      <div> My name is {name} and it used to be {prevName.current}</div>     <>   )}

Ref:

  1. React useRef w3schools
  2. React useRef Youtube

Original Link: https://dev.to/byusa/react-useref-hook-simple-example-2ca4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To