useState in React
As a senior full-stack developer, I am passionate about creating efficient and scalable web applications that enhance the user experience. My expertise in React, Redux, NodeJS, and Laravel has enabled me to lead cross-functional teams and deliver projects that consistently exceed client expectations.
Expert-Level Explanation
useState is a hook that lets you add state to functional components. It returns a pair: the current state and a function that updates it.
Unlike class component state, useState does not automatically merge update objects. You can use useState multiple times in a single component to track different pieces of state.
Creative Explanation
Think of useState as individual switches or buttons in a control panel. Each switch controls a specific aspect of the machine. When you flip a switch or press a button, that particular part of the machine (a piece of state in your component) changes its behaviour or appearance accordingly.
Practical Explanation with Code
Example of using useState:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Here, count is the current state and setCount is the function to update it.
Real-World Example
In an online shopping cart, useState could manage the quantity of items. Each item in the cart has a "quantity" state, and the corresponding "setQuantity" function updates this state when the user adds or removes items.
