Home > Web Front-end > JS Tutorial > Master DOM Manipulation and Performance with React useRef Hook

Master DOM Manipulation and Performance with React useRef Hook

Susan Sarandon
Release: 2024-10-24 03:32:02
Original
629 people have browsed it

Master DOM Manipulation and Performance with React useRef Hook

Understanding React useRef Hook: From Zero to Hero

Introduction

When building applications with React, one key challenge developers face is managing component state and performance. React’s useState hook is widely used for state management, but it can sometimes cause unnecessary re-renders. This is where the useRef hook becomes invaluable. It allows us to interact with the DOM directly, track changes, and store values without triggering component re-renders.

In this guide, we’ll explore the useRef hook step by step, covering its purpose, benefits, and common use cases. By the end, even a beginner will be able to confidently implement useRef to solve various challenges in their React applications.

What Is React useRef Hook?

The useRef hook is part of React’s core hooks API. It returns a mutable object with a .current property, which can be used to store any value you want. Unlike state, changing the .current value does not cause the component to re-render.

Here's the simple syntax for useRef:

const myRef = useRef(initialValue);
Copy after login
Copy after login
  • initialValue: The initial value of the useRef object.
  • myRef.current: The property that stores the reference value.

Why Use useRef?

  • Avoid unnecessary re-renders: State changes trigger re-renders in React, but using useRef allows you to persist values between renders without causing updates.
  • Access DOM elements: Often, we need to interact with native DOM elements, such as focusing an input field. useRef provides an efficient way to do that.
  • Track state changes: You can track values like the previous state or render counts that persist across renders.

Problem: React State Causes Unnecessary Re-renders

In React, state changes trigger re-renders. For performance-critical applications, excessive re-renders can slow down the app. Let’s take an example.

Example Problem: State Causing Re-renders

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
    console.log("Button clicked");
  };

  return (
    <div>
      <p>{count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};
Copy after login
Copy after login

In this example, clicking the button will cause the entire component to re-render, even though you might only care about updating specific data like the count.

Solution: Use useRef to Prevent Re-renders

With useRef, we can store values without causing unnecessary re-renders.

Ref Example to Solve the Problem

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

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

  return (
    <div>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};
Copy after login
Copy after login

In this example, we increment countRef.current without triggering a re-render, because React doesn’t re-render when useRef changes.

Accessing DOM Elements Using useRef

React’s declarative nature abstracts away direct DOM manipulations. But there are times when we need to access DOM elements directly, such as focusing an input field or scrolling to a particular section. This is where useRef comes to the rescue.

Example: Focusing an Input Field

const myRef = useRef(initialValue);
Copy after login
Copy after login

In this example, we assign inputRef to the ref attribute of the input field. The handleFocus function is called when the button is clicked, allowing us to programmatically focus the input field using inputRef.current.focus().

Tracking State Changes Without Re-rendering

Sometimes, you need to track values over time without triggering a re-render. A common use case is to track the previous state of a variable.

Example: Tracking Previous State with useRef

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
    console.log("Button clicked");
  };

  return (
    <div>
      <p>{count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};
Copy after login
Copy after login

In this example, we use useRef to store the previous value. The component renders with the current value, but the previous value is stored in prevValueRef.current and doesn’t trigger a re-render.

Does useRef Cause Re-renders?

No, modifying a useRef object does not cause a re-render. This behavior makes useRef perfect for storing values that you need to persist across renders but don’t want to use as part of the rendering logic.

Example: No Re-rendering on useRef Change

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

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

  return (
    <div>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};
Copy after login
Copy after login

In this example, even though we change renderCountRef.current on every re-render, it doesn’t cause any additional re-renders.

Advanced Example: useRef for Tracking Click Events

Let’s build a more advanced example where we count the number of times a button is clicked without causing re-renders.

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

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

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

In this case, the button’s click count is tracked via clickCountRef.current, but React doesn’t re-render the component.

Common Mistakes with useRef

Forgetting to Initialize the Ref

Always remember to initialize your ref with a value or null.

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

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

  const prevValue = prevValueRef.current;

  return (
    <div>
      <p>Current Value: {value}</p>
      <p>Previous Value: {prevValue}</p>
    </div>
  );
};
Copy after login

Using useRef to Store Component State

Do not use useRef as a substitute for useState. useRef should only be used for values that do not affect rendering. If the value affects the component’s display, use useState.

const NoRenderOnRefChange = () => {
  const renderCountRef = useRef(0);

  useEffect(() => {
    renderCountRef.current += 1;
    console.log("Component re-rendered:", renderCountRef.current);
  });

  return <p>Check the console for render count</p>;
};
Copy after login

Frequently Asked Questions (FAQs)

1. When Should I Use useRef Instead of useState?

Use useRef when you need to store a mutable value without triggering a re-render. For values that affect the UI, use useState.

2. Can I Use useRef for Storing Previous State?

Yes, you can use useRef to store previous values without triggering re-renders, but remember to update the reference in useEffect.

3. Does Modifying useRef Cause Re-renders?

No, modifying useRef.current does not cause re-renders. That’s why it’s ideal for scenarios where you want to avoid unnecessary updates.

4. How Do I Access DOM Elements with useRef?

Assign useRef to the ref attribute of a DOM element, then you can access the DOM element via ref.current.

Conclusion

The useRef hook is a versatile and powerful tool in React that allows developers to store values, track previous states, and interact with DOM elements without causing re-renders. From managing click counts to focusing inputs, useRef opens up opportunities for optimizing performance and providing cleaner, more efficient solutions. With this guide, you now have the knowledge to implement useRef in various scenarios, from beginner-level use cases to more advanced applications.

The above is the detailed content of Master DOM Manipulation and Performance with React useRef Hook. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template