11
React Hooks : Demystifying the useState hook in under 10 minutes [examples + video]
Hey everyone ππ»,
In this article, let us understand about the useState React Hook in under 10 minutes.
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;
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;
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 :
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
11