useRef Hook in React JS

  • In React, the useRef hook is a way to create a mutable reference to a DOM element or a value that persists across renders.
  • The useRef hook returns an object with a current property that can be used to store a value or a reference to a DOM element.
Here's an example of how to use the useRef hook to store a reference to a DOM element:

import { useRef } from 'react';

function MyComponent() {
    const inputRef = useRef(null);

    function handleClick() {
        inputRef.current.focus();
    }

    return (
        <div>
            <input type="text" ref={inputRef} />
            <button onClick={handleClick}>Focus Input</button>
        </div>
    );
}
  • In this example, the useRef hook is used to create a reference to the input element, which is then used in the handleClick function to set the focus on the input element when the button is clicked.
  • The useRef hook can also be used to store a value that persists across renders.
Here's an example of how to use the useRef hook to store a value:

import { useRef } from 'react';

function MyComponent() {
    const countRef = useRef(0);

    function handleClick() {
        countRef.current++;
        console.log(`Count: ${countRef.current}`);
    }

    return (
        <div>
            <button onClick={handleClick}>Increment Count</button>
        </div>
    );
}
  • In this example, the useRef hook is used to create a reference to the count value, which is initially set to 0. The handleClick function updates the count value and logs it to the console.
  • Overall, the useRef hook is a useful tool for creating mutable references to DOM elements or values that persist across renders in React. It can be used to manipulate the DOM, store state, or access values that are shared between different components.

No comments:

Post a Comment