React: useState or useRef?
Asked Answered
D

11

150

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?

Diminish answered 5/6, 2019 at 7:23 Comment(0)
B
273

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.

Bruton answered 5/6, 2019 at 7:36 Comment(3)
Another big difference is that setting a state is asynchronous and setting a ref is synchronous.Buschi
Does it really make such a difference in practice to introduce a separate (confusing) hook? React does many things against optimal performance (registering things in and out), but we should care about avoiding one re-render? How come?Careless
When you use useRef with a native HTML input element your component is uncontrolled input, while using useState its controlledAvitzur
I
15

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.

Impose answered 5/7, 2021 at 17:2 Comment(0)
L
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.

Lineman answered 23/5, 2022 at 5:26 Comment(0)
C
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.

Committal answered 15/11, 2020 at 21:38 Comment(0)
I
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 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 the 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.

  • let's say you need to use an id for the component. if you create it with useState it will change with every rerender.

    const [id,setId]=useState(uuid.v4())

If you want the id not change with every rerender

const id = useRef(uuid.v4());
Interminable answered 8/3, 2022 at 0:59 Comment(0)
S
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]);

  // ...
}
Salmonoid answered 29/12, 2020 at 7:40 Comment(0)
S
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.

Sceptic answered 10/9, 2021 at 4:22 Comment(0)
M
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".

Mccandless answered 26/11, 2021 at 20:43 Comment(0)
E
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.

Evette answered 8/3, 2022 at 9:51 Comment(0)
D
0

As noted in many different places useState updates trigger a render of the component while useRef updates do not.

For the most part having a few guiding principles would help:.

for useState

  • anything used with input / TextInput should have a state that gets updated with the value that you are setting.
  • when you need a trigger to recompute values that are in useMemo or trigger effects using useEffect
  • when you need data that would be consumed by a render that is only available after an async operation done on a useEffect or other event handler. E.g. FlatList data that would need to be provided.

for useRef

  • use these to store data that would not be visible to the user such as event subscribers.
  • for contexts or custom hooks, use this to pass props that are updated by useMemo or useEffect that are triggered by useState/useReducer. The mistake I tend to make is placing something like authState as a state and then when I update that it triggers a whole rerender when that state is actually the final result of a chain.
  • when you need to pass a ref
Dubitation answered 20/12, 2022 at 2:40 Comment(0)
V
0

Simply, If you just need to read a value and never updating the value then use Refs

Viosterol answered 26/5, 2023 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.