app-generator / docs

App Generator - The Official Documentation | AppSeed
https://docs.appseed.us
1 stars 1 forks source link

[React] useRef #111

Open mahfujul-helios opened 1 month ago

mahfujul-helios commented 1 month ago

useRef

What is useRef ?

useRef is another React hook used for accessing and managing references to DOM elements or any mutable value that persists across renders without causing a re-render. It creates a mutable object that persists for the entire lifecycle of the component, even as the component re-renders.

how it's works ?

Under the hood, useRef works by creating a mutable object called a "ref object" using the React library. This ref object persists for the entire lifecycle of the component, even as the component re-renders.

When you call useRef, React creates a ref object and initializes its current property with the value you passed as an argument (if any). This current property serves as a container to hold the mutable value or reference to a DOM element.

When you attach a ref object to a JSX element using the ref attribute, React assigns the DOM element to the current property of the ref object. This allows you to access and manipulate the DOM element directly through the ref object without the need for querying the DOM.

Since the ref object persists between renders, you can freely mutate its current property without triggering a re-render of the component. This makes useRef particularly useful for scenarios where you need to preserve values or references between renders, such as storing references to DOM elements, maintaining values that should not trigger re-renders, or tracking changes across renders.

Overall, useRef provides a way to work with mutable values or references in a React functional component while leveraging React's efficient rendering and reconciliation mechanisms.

Some example of useRef

1. Accessing DOM elements

One of the most common use cases of useRef is accessing DOM elements. Instead of using document.getElementById or other DOM queries, you can use useRef to directly reference an element within your component.

import React, { useRef } from 'react';

const ExampleComponent = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    // Focus the input element on button click
    inputRef.current.focus();
  };

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

2. Storing previous values You can use useRef to store a value that persists across renders but doesn't trigger a re-render when updated. This can be useful when you need to keep track of previous values without triggering unnecessary renders.

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

const PreviousValueComponent = ({ value }) => {
  const prevValueRef = useRef();

  useEffect(() => {
    prevValueRef.current = value;
  }, [value]);

  return (
    <div>
      <p>Current Value: {value}</p>
      <p>Previous Value: {prevValueRef.current}</p>
    </div>
  );
};

3. Working with external libraries Sometimes, when integrating external libraries that expect a mutable reference to some data, useRef can be handy.

import React, { useEffect, useRef } from 'react';
import externalLibrary from 'some-external-library';

const ExternalLibraryComponent = () => {
  const dataRef = useRef([]);

  useEffect(() => {
    // Update the external library with the latest data
    externalLibrary.updateData(dataRef.current);
  }, []);

  // ... rest of the component
};

Remember that since useRef doesn't trigger re-renders, if you need to update the component and reflect the changes in the UI, you should use useState instead. Use useRef only when you need to manage a mutable value or reference that should not affect the component's rendering.

Change the style of an element with useRef

mport React, { useRef } from 'react';

const StyleChangeComponent = () => {
  const divRef = useRef(null);

  const handleColorChange = () => {
    divRef.current.style.backgroundColor = 'lightblue';
  };

  return (
    <div ref={divRef}>
      <p>This is a div element whose style can be changed.</p>
      <button onClick={handleColorChange}>Change Color</button>
    </div>
  );
};

In this example, we use useRef to create a reference divRef, which is attached to the

element. When the "Change Color" button is clicked, the handleColorChange function uses the current property of divRef to access and change the background color of the
element directly.

Change input value with useRef

import React, { useRef } from 'react';

const InputChangeComponent = () => {
  const inputRef = useRef(null);

  const handleChangeValue = () => {
    inputRef.current.value = 'New Value';
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleChangeValue}>Change Input Value</button>
    </div>
  );
};

In this example, useRef is used to create a reference inputRef, which is attached to the element. When the "Change Input Value" button is clicked, the handleChangeValue function accesses the current property of inputRef to change the value of the element directly.

Conclusion

useRef is a powerful hook in React.js that enables developers to efficiently access and modify DOM elements, preserve values, and manage state without triggering unnecessary re-renders. Its versatility makes it an indispensable tool in a developer's toolkit, allowing for enhanced control and performance optimization in React applications. By mastering the use cases and practical implementations demonstrated in this article, developers can leverage the full potential of useRef to build more robust and efficient React components.