How To Use UseRef In React

In this article, we will learn how to use useref in reactjs.

–First of all, we have create react application.

–Then create an App.js file inside the src directory.

–Now import the useref in the App.js file.

import { useRef } from "react";

-write the below code in your file:

import { useState, useEffect, useRef } from "react";
function App() {
  
  const [value, setValue] = useState("");
  const count = useRef(0);
  useEffect(() => {
    count.current = count.current + 1;
  });
  
  return (
    <>
      <h1>Use of UseRef:</h1>
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
      />
      <h1>Your Count: {count.current}</h1>
    </>
  )
}
export default App

-useRef hook allow you to persist values between renders. it stores a mutable value that does not cause a re-render when update.
-useRef access a dom element directly.
-useRef returns a mutable ref object value.

output:

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories