DEV Community

Cover image for React useRef and useParams
G Gokul
G Gokul

Posted on

React useRef and useParams

useRef:

The useRef hook in React is a built-in function that returns a mutable object with a single .current property which persists its value across component renders without triggering a re-render when mutated.

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:

  • In React, you usually let the framework handle the UI.
  • However, if you need to focus an input field, trigger an animation, or measure the size of an element, you need direct access to the underlying HTML element.
  • You link the hook to a JSX node using the ref attribute.

example:

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:

  • Sometimes you need a component to remember a piece of information, but changing that information shouldn't change what's on the screen.

example:

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

difference between useRef vs useState

I

useParams:

  • useParams is a built-in React hook that lets you read dynamic parameter values from the current URL.
  • It is commonly used in frameworks like React Router and Next.js to build dynamic pages.

how it works:

Extracts URL data:It returns an object containing key-value pairs of the dynamic segments defined in your route path.
Example path: If your route is /users/:id and the user visits /users/42, calling const { id } = useParams() will return { id: "42" }.
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)