DEV Community

Serge Jabo Byusa
Serge Jabo Byusa

Posted on

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>

     <>
   )
}
Enter fullscreen mode Exit fullscreen mode

Ref:

  1. React useRef w3schools
  2. React useRef Youtube

Top comments (0)