Bad ways you’re using react – useRef

Share This Post

 

What is useRef?

 

import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);

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

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

 

How programmers misuse useRef

 

import React, { useState, useRef } from "react";

function MyComponent() {
  const [count, setCount] = useState(0);
  const countRef = useRef(0);

  const handleButtonClick = () => {
    setCount(count + 1);
    countRef.current += 1;
  };

  return (
    <div>
      <p>State count: {count}</p>
      <p>Ref count: {countRef.current}</p>
      <button onClick={handleButtonClick}>Increment both counts</button>
    </div>
  );
}

 

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

function MyComponent() {
  const timerIdRef = useRef(null);

  useEffect(() => {
    timerIdRef.current = setInterval(() => {
      console.log("Time's tickin'");
    }, 1000);

    return () => {
      clearInterval(timerIdRef.current);
    };
  }, []);

  return <div>Check your console for some tickin'!</div>;
}

 

// ❌ DON'T DO THIS
function MyComponent({ propValue }) {
  const derivedValueRef = useRef(propValue * 2);

  return <div>Derived value: {derivedValueRef.current}</div>;
}

 

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

function MyComponent({ value }) {
  const valueRef = useRef(value);

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

  const handleButtonClick = () => {
    console.log("The current value is:", valueRef.current);
  };

  return <button onClick={handleButtonClick}>Log current value</button>;
}

In this example, we’re using useEffect to update valueRef.current whenever value changes. Keep them dependencies updated, and you’ll be good to go!

Closing Thoughts

  • Don’t get useRef and useState mixed up — they serve different purposes!
  • useRef ain’t just for DOM refs — it’s got your back for any mutable value you wanna keep across renders.
  • Keep derived state out of useRef to avoid stale data — useMemo, useEffect, or other state management techniques are your friends.
  • Always make sure your dependencies are updated when mixin’ useRef with useEffect or useCallback.

 

Leave a Reply

Digital art dealers

Join our vibrant community of more than 750 members by subscribing to our newsletter. Every Monday, you'll receive a programming meme to kickstart your week.

follow us on

© 2023 Digital Art Dealers. All rights reserved.

%d bloggers like this: