score:202

Accepted answer

The main difference between both is :

useState causes re-render, useRef does not.

The common between them is, both useState and useRef can remember their data after re-renders. So if your variable is something that decides a view layer render, go with useState. Else use useRef

I would suggest reading this article.

score:0

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.

score:0

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".

score:0

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.

score:0

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.

score:1

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]);

  // ...
}

score:1

  • 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.

score:5

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.

score:8

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.


Related Query

More Query from same tag