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.

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 :

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