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?
The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.
Hooks make React so much better because you have simpler code that implements similar functionalities faster and more effectively. You can also implement React state and lifecycle methods without writing classes.
An alternative to the useState Hook, useReducer helps you manage complex state logic in React applications. When combined with other Hooks like useContext , useReducer can be a good alternative to Redux, Recoil or MobX. In certain cases, it is an outright better option.
useReducer may be used as an alternative to useState . It's ideal for complex state logic where there's a dependency on previous state values or a lot of state sub-values.
The reason is if you useState
it rerenders 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 + 1}>{a}</div>; }
In both cases a
changes on click but only when you use useState
the view correctly shows a
's current value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With