Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
Haim763 Avatar asked Jun 05 '19 07:06

Haim763


People also ask

Why should we use useRef in React?

The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

When should I use useRef?

Use useRef if you need to manage focus, text selection, trigger imperative animations or integrating third-party libraries.

Should I use React useState or useState?

Both are the same, import {useState } from 'react' is less verbose and easy for readability and maintenance.

What is the difference between useState and useEffect in React?

The useState hook is used for storing variables that are part of your application's state and will change as the user interacts with your website. The useEffect hook allows components to react to lifecycle events such as mounting to the DOM, re-rendering, and unmounting.


1 Answers

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.

like image 169
Easwar Avatar answered Oct 17 '22 01:10

Easwar