DEV Community

Cover image for Master DOM Manipulation and Performance with React useRef Hook
chintanonweb
chintanonweb

Posted on

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);
Enter fullscreen mode Exit fullscreen mode
  • 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>
  );
};
Enter fullscreen mode Exit fullscreen mode

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>
  );
};
Enter fullscreen mode Exit fullscreen mode

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 FocusInput = () => {
  const inputRef = useRef(null);

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

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleFocus}>Focus Input</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

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 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>
  );
};
Enter fullscreen mode Exit fullscreen mode

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 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>;
};
Enter fullscreen mode Exit fullscreen mode

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 ClickCounter = () => {
  const clickCountRef = useRef(0);

  const handleClick = () => {
    clickCountRef.current += 1;
    console.log("Button clicked", clickCountRef.current, "times");
  };

  return <button onClick={handleClick}>Click me</button>;
};
Enter fullscreen mode Exit fullscreen mode

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 uninitializedRef = useRef(); // Bad
const initializedRef = useRef(null); // Good
Enter fullscreen mode Exit fullscreen mode

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 MyComponent = () => {
  const [count, setCount] = useState(0); // Good for rendering
  const countRef = useRef(0); // Good for tracking without rendering
};
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
katshidev profile image
Nathan Katshi

Nice article!