In react(18.0.0) if you need a state or to toggle a state you might think Manual seems good for example:
let State = 0
function App() {
return State = 1;
}
export default App;
This state wont change.
Now react has a hook designed for this called useState this allows you to manage states.
You can set a string:
import { useState } from "react";
const MyString = useState('Hello, World!');
console.log(MyString);
A boolean:
import { useState } from "react";
const MyBoolean = useState(false);
console.log(MyBoolean);
A number:
import { useState } from "react";
const MyNumber = useState(0);
console.log(MyNumber);
However.. thats still not how you do use state..
if you make a variable using it lets say a number:
import { useState } from "react";
const [MyNumber, SetMyNumber] = useState(0);
for numbers that means now you can switch its state:
SetMyNumber(5);
Comparision table:
| Manual | useState |
|---|---|
| No react hook needed | React hook required |
| No rerender | Rerender on state change |
| Block scoped | Scope & lifetime |
| Not reliable; messy fast | Reliable; but eventuly Redux is better |
| Must use let to change | Const allowed |
| Cant use [VarName, SetVarName] | Required naming syntax is [VarName, SetVarName] |
Wont need redux
|
Eventuly redux is better |
| Messy | Not messy until there are alot; redux is better than 10 useState();
|
Why const?
when using useState(); const is generally better than let or var(Outdated).
Now it changes the state and keeps it internaly too.
With const you can change the state but it wont try and manual redeclare or manual reassign(This is what triggers a syntax error on const!).
now let is unneccesary because we are treating it like a constant.
var is also not recommended because it allows redeclaring and its outdated, let is generaly better.
You can find information about redux here: Official react redux documentation
You can find more information about useState here: Official react useState documentation
Top comments (0)