reactjs
  1. reactjs-useref-hook

ReactJs UseRef Hook

Syntax

const refContainer = useRef(initialValue);

Example

import React, { useRef } from 'react';

function Example() {
  const inputRef = useRef();

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Click to Focus</button>
    </>
  );
}

export default Example;

Output

When the button is clicked, the input field will be focused.

Explanation

The useRef hook in React provides a way to store a mutable value without triggering a re-render of the component. The ref value can be any type of value, similar to state.

Use

Refs can be used to reference DOM elements, store values and implement certain logic. Refs are also useful for passing data between components, setting up focus and measuring the size or position of an element.

Important Points

  • The useRef hook returns a mutable ref object.
  • The ref object can be assigned to any element’s ref attribute.
  • The value of the ref object can persist between renders without causing a re-render.

Summary

The useRef hook provides a way to store a mutable value that can be accessed and modified throughout the component’s lifetime. Use useRef to reference DOM elements, store values, implement certain logic, pass data between components, set up focus, and measure the size or position of an element. Refs can be used to persist data between renders without causing a re-render.

Published on: