React.js useRef Hook Practical Tutorial with Examples of Form Input and State Handling 2020

React.js useRef Hook Practical Tutorial with Examples of Form Input and State Handling 2020

 

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

 

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>
  )
}

 

See also  React.js Tic Tac Toe Computer AI Single or Multiplayer Board Game in Javascript Full Project For Beginners

 

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

 

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>
    </>
  );
}

 

 

 

 

 

Leave a Reply