Welcome folks today in this tutorial we will be looking at React useRef Hook
practical example with form inputs and state handling in react. All the source code of the app is given below. A step by step youtube video is also shown below.
Get Started
In order to get started we need to create our app.js
file of our react application
State Management in React
First example we will look at how to handle state or data using ref copy paste the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import React, { useRef,useEffect, useState } from "react"; export default function App() { const counter = useRef(0); const [number,setNumber] = useState(0) useEffect(() => { counter.current = counter.current + 1; }) const update = () => { setNumber(number + 1) } return ( <div> <h1>{`The component has been re-rendered ${counter.current} times`}</h1> <button onClick={update}>Increase Number</button> {number} </div> ) } |
So now whenever state changes it will be persisted
across future rendering of components. This is not possible with usestate
hook as it will have a infinite loop.
Form Handling
Now we will look at how to focus a input field automatically by attaching a ref
attribute in react like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import React, { useRef } from "react"; export default function App () { const textInput = useRef(); const focusTextInput = () => textInput.current.focus(); return ( <> <input type="text" ref={textInput} /> <br/><br/> <button onClick={focusTextInput}>Focus the text input</button> </> ); } |