Teachnique
      CourseRoadmaps
      Login

      useStateuseEffectuseLayoutEffectuseReduceruseRefforwardRefuseContextClosure Trap in Hooks

      Feedback

      Submit request if you have any questions.

      Course
      useRef

      React Mastery Guide

      Unlock the full potential of React with our comprehensive guide. From basics to advanced techniques, this course covers everything you need to build dynamic, high-performance web applications. Perfect for developers at any level, start mastering React today!

      useRef


      
      Now that we know how to use useState for saving and updating state, how can we save a reference to the DOM?
      This is where useRef comes in.
      import { useEffect, useRef } from 'react';
      import './App.css';
      
      function App() {
      const inputRef = useRef<HTMLInputElement>(null);
      
      useEffect(() => {
      inputRef.current?.focus();
      });
      
      return (
      <>
      <h1>React Hooks</h1>
      <div className="card">
      <input ref={inputRef}></input>
      <p>
      Edit <code>src/App.tsx</code> and save to test Hooks
      </p>
      </div>
      <p className="read-the-docs">
      Click on the Vite and React logos to learn more
      </p>
      </>
      );
      }
      
      export default App;
      

      Let's try it out!

      
      
      The type parameter for useRef specifies the DOM element type you wish to store.
      const xxxRef = useRef<Type of Ref>(null);
      
      In above case, we use ref to save a reference to an input element and then call its focus method in useEffect.
      The DOM element of the ref is stored in the current property.
      A ref is simply an object with a current property.
      
      Another use of useRef is to store a value that persists across renders but does not cause re-renders when the value changes. This is useful for keeping track of stateful values without causing the component to update.
      
      In this example:
      • intervalRef is used to store the interval ID so that it can be cleared later.
      • The value stored in useRef does not trigger re-renders when it is updated.
      • useRef is also used to ensure the interval can be cleared, preventing side effects like memory leaks.