This content originally appeared on DEV Community and was authored by The Nerdy Dev
Hey everyone ??,
In this article, let us understand about the useState React Hook in under 10 minutes.
Understanding useState
I already have an article that covers the useState hook in great detail. Check this out :
React Hooks Part 1 - Understanding useState and useEffect Hooks
The Nerdy Dev ・ May 9 ・ 6 min read
Example 1: Playground
CODE :
import { useState } from 'react';
const LearningState = props => {
const [bgColor, setBgColor] = useState('red');
const turnGreen = () => setBgColor('green');
const reset = () => setBgColor('red');
return (
<div>
<div style={{backgroundColor: bgColor }}>
{bgColor === 'green' ? <p>Color is now green</p>: <p>Red</p>}
</div>
<button onClick={turnGreen}>Turn Green</button>
{bgColor === 'green' && <button onClick={reset}>Reset</button>}
</div>
)
}
export default LearningState;
Example 2: Counter Example, understanding functional form of useState and batching
CODE :
import { useState } from "react";
const Counter = (props) => {
const [counter, setCounter] = useState(0);
console.log('runs...');
const incrementCounter = () => {
// setCounter(counter + 1);
// setCounter(counter + 1);
for(let i=0;i<10;i++) {
setCounter(prevCounter => prevCounter + 1);
}
}
const decrementCounter = () => {
setCounter(previousCounter => previousCounter - 1);
setCounter(previousCounter => previousCounter - 1);
setCounter(previousCounter => previousCounter - 1);
}
return (
<div>
<h1>Counter : {counter} </h1>
<button onClick={incrementCounter}>Increment Counter</button>
<button onClick={decrementCounter}>Decrement Counter</button>
</div>
)
}
export default Counter;
Video ?
So this was it for this one.
If you are looking to learn Web Development, I have curated a FREE course for you on my YouTube Channel, check the below article :
(2021) - Web Developer Full Course : HTML, CSS, JavaScript, Node.js and MongoDB
The Nerdy Dev ・ Apr 28 ・ 2 min read
Spare 2 Hours ? If so, utilize them by creating these 10 JavaScript Projects in under 2 Hours
?? Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
?? Check out my YouTube Channel : https://youtube.com/thenerdydev
This content originally appeared on DEV Community and was authored by The Nerdy Dev
The Nerdy Dev | Sciencx (2021-06-28T06:12:44+00:00) React Hooks : Demystifying the useState hook in under 10 minutes [examples + video]. Retrieved from https://www.scien.cx/2021/06/28/react-hooks-demystifying-the-usestate-hook-in-under-10-minutes-examples-video/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.