Moshe Nagar
Moshe Nagar

Reputation: 1421

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?

Upvotes: 130

Views: 77604

Answers (8)

vairavel flash
vairavel flash

Reputation: 83

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.sstatic.net/vKp5P.png]

Upvotes: 0

Sherif eldeeb
Sherif eldeeb

Reputation: 2186

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

Upvotes: 0

marzelin
marzelin

Reputation: 11600

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.

Upvotes: 137

Mike
Mike

Reputation: 124

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.

Upvotes: 5

Drew Reese
Drew Reese

Reputation: 202751

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

Upvotes: 33

schogges
schogges

Reputation: 459

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.

Upvotes: 3

Diamond
Diamond

Reputation: 3428

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>;
}

Upvotes: 1

10100111001
10100111001

Reputation: 1832

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.

Upvotes: 2

Related Questions