'React: useState or useRef?

I am reading about React useState() and useRef() at "Hooks FAQ" and I got confused about some of the use cases that seem to have a solution with useRef and useState at the same time, and I'm not sure which way it the right way.

From the "Hooks FAQ" about useRef():

"The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class."

With useRef():

function Timer() {
  const intervalRef = useRef();

  useEffect(() => {
    const id = setInterval(() => {
      // ...
    });
    intervalRef.current = id;
    return () => {
      clearInterval(intervalRef.current);
    };
  });

  // ...
}

With useState():

function Timer() {
  const [intervalId, setIntervalId] = useState(null);

  useEffect(() => {
    const id = setInterval(() => {
      // ...
    });
    setIntervalId(id);
    return () => {
      clearInterval(intervalId);
    };
  });

  // ...
}

Both examples will have the same result, but which one it better - and why?



Solution 1:[1]

useRef is useful when you want to track value change, but don't want to trigger re-render or useEffect by it.

Most use case is when you have a function that depends on value, but the value needs to be updated by the function result itself.

For example, let's assume you want to paginate some API result:

const [filter, setFilter] = useState({});
const [rows, setRows] = useState([]);
const [currentPage, setCurrentPage] = useState(1);

const fetchData = useCallback(async () => {
  const nextPage = currentPage + 1;
  const response = await fetchApi({...filter, page: nextPage});
  setRows(response.data);
  if (response.data.length) {
    setCurrentPage(nextPage);
  }
}, [filter, currentPage]);

fetchData is using currentPage state, but it needs to update currentPage after successful response. This is inevitable process, but it is prone to cause infinite loop aka Maximum update depth exceeded error in React. For example, if you want to fetch rows when component is loaded, you want to do something like this:

useEffect(() => {
  fetchData();
}, [fetchData]);

This is buggy because we use state and update it in the same function.

We want to track currentPage but don't want to trigger useCallback or useEffect by its change.

We can solve this problem easily with useRef:

const currentPageRef = useRef(0);

const fetchData = useCallback(async () => {
  const nextPage = currentPageRef.current + 1;
  const response = await fetchApi({...filter, page: nextPage});
  setRows(response.data);
  if (response.data.length) {
     currentPageRef.current = nextPage;
  }
}, [filter]);

We can remove currentPage dependency from useCallback deps array with the help of useRef, so our component is saved from infinite loop.

Solution 2:[2]

Basically, We use UseState in those cases, in which the value of state should be updated with re-rendering.

when you want your information persists for the lifetime of the component you will go with UseRef because it's just not for work with re-rendering.

Solution 3:[3]

If you store the interval id, the only thing you can do is end the interval. What's better is to store the state timerActive, so you can stop/start the timer when needed.

function Timer() {
  const [timerActive, setTimerActive] = useState(true);

  useEffect(() => {
    if (!timerActive) return;
    const id = setInterval(() => {
      // ...
    });
    return () => {
      clearInterval(intervalId);
    };
  }, [timerActive]);

  // ...
}

If you want the callback to change on every render, you can use a ref to update an inner callback on each render.

function Timer() {
  const [timerActive, setTimerActive] = useState(true);
  const callbackRef = useRef();

  useEffect(() => {
    callbackRef.current = () => {
      // Will always be up to date
    };
  });

  useEffect(() => {
    if (!timerActive) return;
    const id = setInterval(() => {
      callbackRef.current()
    });
    return () => {
      clearInterval(intervalId);
    };
  }, [timerActive]);

  // ...
}

Solution 4:[4]

  • Counter App to see useRef does not rerender

If you create a simple counter app using useRef to store the state:

import { useRef } from "react";

const App = () => {
  const count = useRef(0);

  return (
    <div>
      <h2>count: {count.current}</h2>
      <button
        onClick={() => {
          count.current = count.current + 1;
          console.log(count.current);
        }}
      >
        increase count
      </button>
    </div>
  );
};

If you click on the button, <h2>count: {count.current}</h2> this value will not change because component is NOT RE-RENDERING. If you check the console console.log(count.current), you will see that value is actually increasing but since the component is not rerendering, UI does not get updated.

If you set the state with useState, clicking on the button would rerender the component so UI would get updated.

  • Prevent the unnecessary re-renderings while typing into input.

Rerendering is an expensive operation. In some cases you do not want to keep rerendering the app. For example, when you store the input value in state to create a controlled component. In this case for each keystroke you would rerender the app. If you use the ref to get a reference to the DOM element, with useState you would rerender the component only once:

import { useState, useRef } from "react";
const App = () => {
  const [value, setValue] = useState("");
  const valueRef = useRef();
 
  const handleClick = () => {
    console.log(valueRef);
    setValue(valueRef.current.value);
  };
  return (
    <div>
      <h4>Input Value: {value}</h4>
      <input ref={valueRef} />
      <button onClick={handleClick}>click</button>
    </div>
  );
};
  • Prevent the infinite loop inside useEffect

to create a simple flipping animation, we need to 2 state values. one is a boolean value to flip or not in an interval, another one is to clear the subscription when we leave the component:

const [isFlipping, setIsFlipping] = useState(false);
  
  let flipInterval = useRef<ReturnType<typeof setInterval>>();
  useEffect(() => {
    startAnimation();
    return () => flipInterval.current && clearInterval(flipInterval.current);
  }, []);

  const startAnimation = () => {
    flipInterval.current = setInterval(() => {
      setIsFlipping((prevFlipping) => !prevFlipping);
    }, 10000);
  };

setInterval returns an id and we pass it to clearInterval to end the subscription when we leave the component. flipInterval.current is either null or this id. If we did not use ref here, everytime we switched from null to id or from id to null, this component would rerender and this would create an infinite loop.

  • If you do not need to update UI, use useRef to store state variables.

Let's say in react native app, we set the sound for certain actions which have no effect on UI. For one state variable it might not be that much performance savings but If you play a game and you need to set different sound based on game status.

const popSoundRef = useRef<Audio.Sound | null>(null);
const pop2SoundRef = useRef<Audio.Sound | null>(null);
const winSoundRef = useRef<Audio.Sound | null>(null);
const lossSoundRef = useRef<Audio.Sound | null>(null);
const drawSoundRef = useRef<Audio.Sound | null>(null);

If I used useState, I would keep rerendering every time I change a state value.

Solution 5:[5]

You can also use useRef to ref a dom element (default HTML attribute)

eg: assigning a button to focus on the input field.

whereas useState only updates the value and re-renders the component.

Solution 6:[6]

It really depends mostly on what you are using the timer for, which is not clear since you didn't show what the component renders.

  • If you want to show the value of your timer in the rendering of your component, you need to use useState. Otherwise, the changing value of your ref will not cause a re-render and the timer will not update on the screen.

  • If something else must happen which should change the UI visually at each tick of the timer, you use useState and either put the timer variable in the dependency array of a useEffect hook (where you do whatever is needed for the UI updates), or do your logic in the render method (component return value) based on the timer value. SetState calls will cause a re-render and then call your useEffect hooks (depending on the dependency array). With a ref, no updates will happen, and no useEffect will be called.

  • If you only want to use the timer internally, you could use useRef instead. Whenever something must happen which should cause a re-render (ie. after a certain time has passed), you could then call another state variable with setState from within your setInterval callback. This will then cause the component to re-render.

Using refs for local state should be done only when really necessary (ie. in case of a flow or performance issue) as it doesn't follow "the React way".

Solution 7:[7]

useRef() only updates the value not re-render your UI if you want to re-render UI then you have to use useState() instead of useRe. let me know if any correction needed.

Solution 8:[8]

The main difference between useState and useRef are -

  1. The value of the reference is persisted (stays the same) between component re-rendering,

  2. Updating a reference using useRefdoesn't trigger component re-rendering. However, updating a state causes component re-rendering

  3. The reference update is synchronous, the updated referenced value is immediately available, but the state update is asynchronous - the value is updated after re-rendering.

To view using codes:

import { useState } from 'react';
function LogButtonClicks() {
  const [count, setCount] = useState(0);
  
  const handle = () => {
    const updatedCount = count + 1;
    console.log(`Clicked ${updatedCount} times`);
    setCount(updatedCount);
  };
  console.log('I rendered!');
  return <button onClick={handle}>Click me</button>;
}

Each time you click the button, it will show I rendered!

However, with useRef

import { useRef } from 'react';
function LogButtonClicks() {
  const countRef = useRef(0);
  
  const handle = () => {
    countRef.current++;
    console.log(`Clicked ${countRef.current} times`);
  };
  console.log('I rendered!');
  return <button onClick={handle}>Click me</button>;
}

I am rendered will be console logged just once.

Solution 9:[9]

There are 2 things you need to take care of:

  1. Make sure that the data for this column is added to supplemental log. You can make sure this happens - with running:

    add trandata my_test cols(date_added)
    

or by running SQL in the database:

   alter table my_test add supplemental log group grp1 (date_added) always;
  1. You need to make sure that this column gets captured by extract process. To make sure this happens you should use in extract parameter:

    table my_test, cols(date_added);
    

This should be enough to include this columns in the trail. You can verify trail file if it actually contains date_added column;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 glinda93
Solution 2 Ghulam Meeran
Solution 3
Solution 4
Solution 5 m4n0
Solution 6
Solution 7 CRN
Solution 8 Bidisha Das
Solution 9