React Hooks - using useState vs just variables
Asked Answered
H

8

123

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?

Houseroom answered 5/10, 2019 at 21:25 Comment(1)
You are comparing 2 different things though. The second function with hooks has the ability to update the data. The first one is not really doing anything. You could have just initialized it with let a = 1; return <div>{a}</div> and you will get the same result.Camboose
F
134

The reason is if you useState it re-renders 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 = a + 1}>{a}</div>;
}

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

Fetching answered 5/10, 2019 at 21:31 Comment(5)
Thanks! So if I don't need to render the view - only a way to organize my data(props) into some array - I can use 'let' ? Its works for me, I just want to know its okay and acceptable.Houseroom
@MosheNagar if you derive your data from props it's recommended to use local variables instead of keeping data in state because the component will rerender on prop change anyway so the view will be in sync with the data. Putting them in state would only cause unnecessary rerender - first on prop change, then on state change.Fetching
One more way of looking at this answer is to think that in the second case, the variable a will be garbage collected after it finishes executing, while in the first one, since it leverages useState it will preserve the value of aHers
He could still use useRef if he didn't want to re-render the view. The question remains if he should use local variables or React references. E.g. if you have a timeout you need to clear, or an on-going http request using axios, do you store the timeout or axios source in a variable or in a React ref?Sickroom
@Sickroom The general rule is use local vars for derived state. For anything else use useRef (if you don't want rerender) or useState (if you want rerender). In the case of timers, as they are side effects, they should be started in useEffect hook. If you want timerId only for cleanup purposes, you can keep it in handler's local variable. If you want to be able to clear the timer from other place in the component, you should use useRef. Storing timerId in a component's local variable would be a mistake since local vars are "reset" on each render.Fetching
B
28

Local variables will get reset every render upon mutation whereas state will update:

function App() {
  let a = 0; // reset to 0 on render/re-render
  const [b, setB] = useState(0);

  return (
    <div className="App">
      <div>
        {a}
        <button onClick={() => a++}>local variable a++</button>
      </div>
      <div>
        {b}
        <button onClick={() => setB(prevB => prevB + 1)}>
          state variable b++
        </button>
      </div>
    </div>
  );
}

Edit serene-galileo-ml3f0

Brachial answered 5/10, 2019 at 21:37 Comment(3)
Local variables will get reset every render upon mutation whereas state will update. It's correct with the functional component. How about the class component?Eulaliaeulaliah
@NguyễnVănPhong If you are referring to class properties, no, they live outside the component lifecycle. If you are referring to any variables declared in the render lifecycle method (for example), these would be redeclared each render just like in functional components.Brachial
That makes sense. +1Eulaliaeulaliah
F
4

It is perfectly acceptable to use standard variables. One thing I don't see mentioned in other answers is that if those variables use state-variables, their value will seemingly update on a re-render event.

Consider:

import {useState} from 'react';

function NameForm() {
  // State-managed Variables
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');

  // State-derived Variables
  const fullName = `${firstName} ${lastName}`;

  return (
    <input value={firstName} onChange={e => setFirstName(e.target.value)} />
    <input value={lastName} onChange={e => setLastName(e.target.value)} />
    {fullName}
  );
}

/*
Description: 
  This component displays three items:
    - (2) inputs for _firstName_ and _lastName_ 
    - (1) string of their concatenated values (i.e. _lastName_)
  If either input is changed, the string is also changed.
*/

Updating firstName or lastName sets the state and causes a re-render. As part of that process fullName is assigned the new value of firstName or lastName. There is no reason to place fullName in a state variable.

In this case it is considered poor design to have a setFullName state-setter because updating the firstName or lastName would cause a re-render and then updating fullName would cause another re-render with no perceived change of value.


In other cases, where the view is not dependent on the variable, it is encouraged to use local variables; for instance when formatting props values or looping; regardless if whether the value is displayed.

Falconer answered 7/1, 2023 at 23:12 Comment(1)
I must have not read some of the top comments as they do note the re-render when state changes. My initial comment is less concise, though possible more comprehensive, so I'm leaving it.Falconer
T
3
function Foo() {
    const [a, setA] = useState(0);
    if (a != 1) setA(1); // to avoid infinite-loop
    return <div>{a}</div>;
}

is equivalent to

class Foo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            a: 0
        };
    }
    // ...
}

What useState returns are two things:

  1. new state variable
  2. setter for that variable

if you call setA(1) you would call this.setState({ a: 1 }) and trigger a re-render.

Testee answered 5/10, 2019 at 21:35 Comment(0)
M
2

Your first example only works because the data essentially never changes. The enter point of using setState is to rerender your entire component when the state hanges. So if your example required some sort of state change or management you will quickly realize change values will be necessary and to do update the view with the variable value, you will need the state and rerendering.

Mehala answered 5/10, 2019 at 21:35 Comment(0)
M
1

Updating state will make the component to re-render again, but local values are not.

In your case, you rendered that value in your component. That means, when the value is changed, the component should be re-rendered to show the updated value.

So it will be better to use useState than normal local value.

function Foo() {
    let a = 0;
    a = 1; // there will be no re-render.
    return <div>{a}</div>;
}

function Foo() {
    const [a, setA] = useState(0);
    if (a != 1) setA(1); // re-render required
    return <div>{a}</div>;
}
Minstrel answered 5/10, 2019 at 21:35 Comment(0)
P
0

Local vaiables value doesn't change on render, while state holds the variable value between renders.

import React,{useState} from 'react'
import ReactDOM from 'react-dom'

function App() {
  let a = 0;
    a = 1;
    const [b, setB] = useState(2);
    console.log('a->',a)
    console.log('b->',b)

  return (
    <>
  <div>{a}</div>
<div onClick={() => a = a + 1}> onclick {a}</div>
  <div>{b}</div>
  <div onClick={() => setB(b + 1)}>onclick{b}</div>;
  </>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

[Output Image] [https://i.stack.imgur.com/vKp5P.png]

Portend answered 13/8, 2023 at 14:40 Comment(1)
You have an empty image link.Skimp
H
0

as a side note, this behavior is a little bit different in Angular, as the view renders whenever the variable is updated without using useState()

Angular

export class MyComponent{
 count = 0;

 updateCount(){
   this.count++;
}

}

in HTML:

<button (click)="updateCount()">{{ count }}</button>

however, this behavior is different in Reactjs

export function MyComponent(){
 let count1=0;
 let [count2, setCountState] = useState(0)

 function updateCounts(){
  count1++;
  setCountState(count2++);
  console.log({count1, count2})
  }

 return (
   <button onClick={updateCounts}> {count1} / {count2} </button>
  )

both count1 and count2 will be updated on each click, you can confirm by inspecting your console. but only count2 causes the view to be rerendered with the new state

Horrorstruck answered 20/10, 2023 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.