useRef hook explained react

useRef hook explained react

·

4 min read

↠ Hooks introduced in React 16.8, allow us to use stateful logic, lifecycle methods, and side-effects in Functional Components.

↠ The main use of the useRef hook in the react is, The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated.

↠ useRef is one of the standard hooks provided by React. It will return an object that you can use during the whole lifecycle of the component. useRef hook is to access a DOM child directly

↠ useRef is used to remember previous value of a state variable

⭐The useRef Hook allows you to persist values between renders. ⭐ It can be used to store a mutable value that does not cause a re-render when updated. ⭐ It can be used to access a DOM element directly.

why we have to use useRef hook

➜ useRef needed to manage focus, text selection, trigger imperative animations or integrating third-party libraries etc.

➜ What is the difference between useRef and useState? useState is a hook which is used to update the state in functional component. useRef is a hook which provides a way to access to the DOM.

Lets see with an example

As we know while using hooks first we need import the hooks which we are using in the following

import React, { useState , useRef } from "react";

Now we have to create a state with any name you want and don't assign the useState value leave empty and return a input Attribute with type="text" placeholde="randomInput" , value={randomInput} as follows

import React, {useState, useRef} from "react";

export default function App() {
   const[randomInput, setrandomInput] = useState("")

 return (
    <main className="App">
     <input 
       type="text"
       placeholder="randomInput"
       value={randomInput}
      />
    </main>
  );
}

The next thing we have to do is to make count the number of renders, i.e The number of text input we give in the input box with name or any random input it should count the each and every text entered.

This is done by useRef say ⇉ const renders = useRef(0);

☆ The const variable renders store the useRef value which is primarly assigned to zero

Now onChage function which assigned to handleChange with const variable

const handleChange = (e) => {
    setRandomInput(e.target.value);
    renders.current++;
  }
<input
  onChange={handleChange}
/>

Now add the handleChange value to the react component as follows and render the text you entered in the input box

import React, {useState, useRef} from "react";

export default function App() {
  const[randomInput, setRandomInput] = useState("")
  const renders = useRef(0);

  const handleChange = (e) => {
    setRandomInput(e.target.value);
    renders.current++;
  }

  return (
    <main className="App">
      <input 
      type="text"
      placeholder="randomInput"
      value={randomInput}
      onChange={handleChange}
         />

   <p>Renders: {renders.current}</p>

   <p> Text you Entered :- {randomInput}</p>
    </main>
  );
}

OUTPUT

randomInput.png

☆↠ e is the event, which in this case is change, target is the element that triggered the event, which in this case is the input, and value is the value of the input element

☆↠ The e is the argument of an event handler you attach to a certain event on a certain component,, in this case the onChange event. Events are objects with certain properties, and e.target almost always represents a DOM element

Before you scroll down make sure that you have understood the above till know

➣ Now , The another const variable say "const inputRef = useRef();"

➣ Add the button with the onClick event says focusOnInput "< button onClick={focusOnInput}>FOCUS</ button >"

➣ with the reference in the input "ref={inputRef}"

➣ As we added onClick function assign to focusOnInput using const variable const focusOnInput = () => { inputRef.current.focus(); }

And you are ready to go, no matter where is the cursor on the screen when you click on the Focus button it redirects to the input box

import React, {useState, useRef} from "react";

export default function App() {
  const[randomInput, setRandomInput] = useState("")

  const renders = useRef(0);

  const inputRef = useRef("");

  const focusOnInput = () => {
    inputRef.current.focus();
  }


  const handleChange = (e) => {
    setRandomInput(e.target.value);
    renders.current++;
  }

  return (
    <main className="App">
      <input 
      ref={inputRef}
      type="text"
      placeholder="randomInput"
      value={randomInput}
      onChange={handleChange}
         />

   <p>Renders: {renders.current}</p>

   <p> Text you Entered :- {randomInput}</p>

   <button onClick={focusOnInput}>FOCUS</button>
    </main>
  );
}

OUTPUT

ref23.png when you click on the Focus button it redirects to the input box (and added to simple style to button and input )

Thanks for reading🌻💐
Have a good day...😊🙂