Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks - using useState vs just variables

React Hooks give us useState option, and I always see Hooks vs Class-State comparisons. But what about Hooks and some regular variables?

For example,

function Foo() {     let a = 0;     a = 1;     return <div>{a}</div>; } 

I didn't use Hooks, and it will give me the same results as:

function Foo() {     const [a, setA] = useState(0);     if (a != 1) setA(1); // to avoid infinite-loop     return <div>{a}</div>; } 

So what is the diffrence? Using Hooks even more complex for that case...So why start using it?

like image 279
Moshe Nagar Avatar asked Oct 05 '19 21:10

Moshe Nagar


People also ask

Why we use useState in React Hooks?

The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.

Is it better to use Hooks in React?

Hooks make React so much better because you have simpler code that implements similar functionalities faster and more effectively. You can also implement React state and lifecycle methods without writing classes.

What can I use instead of useState in React?

An alternative to the useState Hook, useReducer helps you manage complex state logic in React applications. When combined with other Hooks like useContext , useReducer can be a good alternative to Redux, Recoil or MobX. In certain cases, it is an outright better option.

Which React hook is an alternative to useState () hook?

useReducer may be used as an alternative to useState . It's ideal for complex state logic where there's a dependency on previous state values or a lot of state sub-values.


1 Answers

The reason is if you useState it rerenders the view. Variables by themselves only change bits in memory and the state of your app can get out of sync with the view.

Compare this examples:

function Foo() {     const [a, setA] = useState(0);     return <div onClick={() => setA(a + 1)}>{a}</div>; }  function Foo() {     let a = 0;     return <div onClick={() => a + 1}>{a}</div>; } 

In both cases a changes on click but only when you use useState the view correctly shows a's current value.

like image 174
marzelin Avatar answered Sep 19 '22 17:09

marzelin