ReasonJun

React: useRef 본문

Frontend/React

React: useRef

ReasonJun 2023. 6. 14. 19:09
728x90

In React, the useRef hook is used to create a mutable reference that persists across renders. It provides a way to access and interact with DOM elements or values that may change over time without triggering a re-render of the component.

 

The useRef hook returns a mutable ref object with a .current property. This property can hold any value and remains the same between renders. When the .current value is updated, the component will not re-render.

Here are a few common use cases for useRef:

  1. Accessing DOM elements: You can use useRef to reference DOM elements and interact with them directly. For example, you can focus an input field or trigger other imperative actions on the DOM element.
  2. Storing values between renders: If you have a value that needs to persist between renders but doesn't affect the component's visual output, you can store it in a useRef value.

Here's an example that demonstrates how to use useRef to access a DOM element and store a value:

import React, { useRef, useEffect } from 'react';

const MyComponent = () => {
  const inputRef = useRef(null);
  const countRef = useRef(0);

  useEffect(() => {
    // Focus the input field on component mount
    inputRef.current.focus();
  }, []);

  const handleClick = () => {
    countRef.current += 1;
    console.log('Button clicked', countRef.current);
  };

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

export default MyComponent;

By using useRef, you can access and store values that persist across renders without triggering re-renders of the component. This makes it useful for managing mutable values or interacting with DOM elements directly.

728x90
Comments