Discover how a tiny hook can save you from messy code and endless bugs!
Why useState hook introduction in React? - Purpose & Use Cases
Imagine you want to build a simple counter on a webpage that updates every time you click a button. You try to change the number by directly modifying the page content with plain JavaScript.
Manually updating the page content is tricky and slow. You have to find the right element, change its text, and make sure the page updates correctly. It's easy to make mistakes and the code becomes messy as the app grows.
The useState hook in React lets you store and update values easily. When the value changes, React automatically updates the page for you, keeping your code clean and simple.
const button = document.querySelector('button'); let count = 0; button.onclick = () => { count++; document.querySelector('#count').textContent = count; };
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>{count}</button>; }
It makes building interactive, dynamic user interfaces easy and reliable by managing state changes smoothly.
Think of a shopping cart where the number of items updates instantly as you add or remove products, without refreshing the page.
Manual DOM updates are error-prone and hard to maintain.
useState handles state and UI updates automatically.
This leads to cleaner code and better user experiences.