115

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?

Moshe Nagar
  • 1,271
  • 2
  • 9
  • 7
  • 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
    {a}
    ` and you will get the same result.
    – Yathi Oct 06 '19 at 01:14

7 Answers7

123

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.

marzelin
  • 10,790
  • 2
  • 30
  • 49
  • 4
    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. – Moshe Nagar Oct 06 '19 at 17:50
  • 26
    @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. – marzelin Oct 06 '19 at 19:18
  • 4
    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 `a` – João Marcos Gris Nov 10 '19 at 04:11
  • 4
    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? – Tom Dec 02 '19 at 00:32
  • 8
    @Tom 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. – marzelin Dec 02 '19 at 10:12
25

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

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • `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? – Nguyễn Văn Phong Apr 28 '21 at 04:30
  • 2
    @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. – Drew Reese Apr 28 '21 at 04:51
  • 1
    That makes sense. +1 – Nguyễn Văn Phong Apr 28 '21 at 04:53
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.

schogges
  • 351
  • 5
  • 12
3

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.

Mike
  • 94
  • 4
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.

10100111001
  • 1,832
  • 1
  • 11
  • 7
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>;
}
Diamond
  • 3,470
  • 2
  • 19
  • 39
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]