DEV Community

Cover image for React useRef and useparams
Keerthana M
Keerthana M

Posted on

React useRef and useparams

React useRef Hook:

  • 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.
  • If we tried to count how many times our application renders using the useState Hook, we would be caught in an infinite loop since this Hook itself causes a re-render.
  • To avoid this, we can use the useRef Hook.

syntax:

const myRef = useRef(0);
Enter fullscreen mode Exit fullscreen mode

You can read or update this value at any time using myRef.current.

Two Main Use Cases:

  1. Direct DOM Manipulation:
  • DOM manipulation allows developers to interact with and modify the structure, style, and content of web pages.
  • In this article, we'll explore the fundamentals of DOM manipulation in JavaScript, breaking down complex concepts into easy-to-understand snippets.
import { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef(null); // 1. Create the ref box

  const handleClick = () => {
    // 3. Access the DOM node directly and focus it
    inputRef.current.focus(); 
  };

  return (
    <>
      {/* 2. Link the ref box to the HTML input element */}
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus the input</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

2.Storing Data That Shouldn't Cause Re-Renders:

  • Use useRef to store values that persist across renders without triggering re-renders. This allows you to track values or DOM elements without affecting the rendering cycle.
  • Avoid using useState for data that should not change frequently. Instead, use useRef for tracking values that persist across multiple renders.
import { useRef } from 'react';

function Timer() {
  const timerIdRef = useRef(null);

  const startTimer = () => {
    // Storing the interval ID without forcing a re-render
    timerIdRef.current = setInterval(() => {
      console.log('Tick');
    }, 1000);
  };

  const stopTimer = () => {
    // Clearing the interval using the stored ID
    clearInterval(timerIdRef.current);
  };

  return (
    <div>
      <button onClick={startTimer}>Start</button>
      <button onClick={stopTimer}>Stop</button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

useParams:

  • The useParams hook in React Router allows you to access the dynamic parameters from the current URL.
  • This is particularly useful for handling routes with dynamic segments.

Syntax

const { param1, param2, ... } = useParams();
Enter fullscreen mode Exit fullscreen mode
  • param1, param2, etc., are route parameters defined in the path.
  • UseParams returns an object where keys are the parameter names and values are the values from the URL.

Extracts URL data:

  • It returns an object containing key-value pairs of the dynamic segments defined in your route path.

Dynamic rendering:

  • You can use these extracted values to fetch specific data or display user-specific information on your webpage

example:
1. Define the Route with a Colon (:):

  • In your routing setup, you mark the dynamic parts of your URL path using a colon (:) followed by a variable name.
import { BrowserRouter, Routes, Route } from "react-router-dom";
import UserProfile from "./UserProfile";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        {/* ':id' is the dynamic parameter here */}
        <Route path="/user/:id" element={<UserProfile />} />
      </Routes>
    </BrowserRouter>
  );
}
Enter fullscreen mode Exit fullscreen mode

2. Extract the Parameter inside the Component:

  • If a user visits /user/42 or /user/santhosh, you use useParams() inside that component to grab that specific value.
import { useParams } from "react-router-dom";

function UserProfile() {
  // Destructure the 'id' parameter directly from useParams()
  const { id } = useParams(); 

  return (
    <div>
      <h2>User Profile</h2>
      <p>The current User ID is: <strong>{id}</strong></p>
    </div>
  );
}

export default UserProfile;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)