Holding Mutable Values Across Renders
×


Holding Mutable Values Across Renders

689

🔁 What Are Mutable Values Across Renders?

In React, most component values are tied to renders — like useState. But sometimes you need to store a value that:

  • Persists across renders ✅
  • Doesn’t cause re-render on change 🚫
  • Can be updated and accessed imperatively 📦
This is what we mean by holding mutable values across renders — and useRef is the best tool for it. 🧠

🧠 useRef: The Key to Persisted Mutable Values

The useRef hook lets you store a mutable object that doesn’t change between renders. It has a single property: .current, where you store your value.


import { useRef } from 'react';

function Timer() {
  const intervalRef = useRef(null); // Mutable value across renders

  const startTimer = () => {
    intervalRef.current = setInterval(() => {
      console.log('Tick...');
    }, 1000);
  };

  const stopTimer = () => {
    clearInterval(intervalRef.current);
  };

  return (
    
); }
Here, intervalRef persists even as the component re-renders, but updates to it don’t cause new renders — which is perfect for timers and subscriptions. ⏱️

📦 Common Use Cases

  • 📌 Holding timer IDs or animation frames
  • 🎯 Storing latest props or values in async callbacks
  • 📍 Tracking if a component is mounted
  • 💡 Caching measurements or positions

🚫 Why Not useState?

useState is reactive — when the value changes, React re-renders the component. That’s great for UI-driven data. But if the value is only used behind the scenes (like a reference, cache, or flag), useRef is better because:

  • ✅ No re-renders on change
  • ✅ Simple .current syntax
  • ✅ Perfect for side effects, event handlers, and refs

🧪 Example: Persisting Previous Value

Let’s say you want to compare the current and previous count without triggering a re-render:


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

function PreviousValueExample() {
  const [count, setCount] = useState(0);
  const prevCount = useRef();

  useEffect(() => {
    prevCount.current = count;
  }, [count]);

  return (
    
Current: {count}

Previous: {prevCount.current}

); }
🔥 This is a classic pattern where useRef holds a mutable value that updates without triggering re-renders.

🧠 Best Practices

  • ✅ Use useRef when the value doesn’t affect UI
  • ✅ Avoid triggering logic based on ref.current changes
  • ✅ Combine with useEffect for lifecycle-style logic
  • 🚫 Don’t overuse useRef as a hidden state replacement

🧵 Bonus: useRef for Mount Flags

Prevent state updates on unmounted components with a mount flag:


function AsyncComponent() {
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;

    fetchData().then(data => {
      if (isMounted.current) {
        // Safe to update state
      }
    });

    return () => {
      isMounted.current = false;
    };
  }, []);
}
📌 This helps prevent memory leaks and errors in async operations.

🚀 Final Thoughts

Holding mutable values across renders is a powerful concept that enables advanced, performant logic in React. By using useRef, you can store and manage dynamic values — like timers, flags, previous states, and more — without triggering unwanted re-renders. Learn it well, and you’ll unlock a whole new level of control in React! ⚡



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat