admin管理员组文章数量:1134244
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?
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?
Share Improve this question asked Oct 5, 2019 at 21:25 Moshe NagarMoshe Nagar 1,4212 gold badges10 silver badges7 bronze badges 1 |8 Answers
Reset to default 137The 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.
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>
);
}
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.
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:
- new state variable
- setter for that variable
if you call setA(1)
you would call this.setState({ a: 1 })
and trigger a re-render.
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.
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>;
}
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
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]
本文标签: javascriptReact Hooksusing useState vs just variablesStack Overflow
版权声明:本文标题:javascript - React Hooks - using useState vs just variables - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736827788a1954567.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
let a = 1; return <div>{a}</div>
and you will get the same result. – Yathi Commented Oct 6, 2019 at 1:14