An Interest In:
Web News this Week
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
June 8, 2022 05:40 pm GMT
Original Link: https://dev.to/byusa/react-useref-hook-simple-example-2ca4
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:
Original Link: https://dev.to/byusa/react-useref-hook-simple-example-2ca4
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To