useState is a react hook, which creates a
"state variable" Which helps us to track state in components
& updates the user interface when state changes.
Example - 1
import React, { useState } from "react";
import ReactDOM from "react-dom/client";
function FavoriteColor() {
const [color, setColor] = useState("red");
function changeColor(color) {
setColor(color);
}
return (
<>
<h1>
My favorite color is
<div style={{ color: color }}>{color}</div>
</h1>
<button type="button" onClick={() => changeColor("blue")}>
Blue
</button>
<button type="button" onClick={() => changeColor("red")}>
Red
</button>
<button type="button" onClick={() => changeColor("pink")}>
Pink
</button>
<button type="button" onClick={() => changeColor("green")}>
Green
</button>
</>
);
}
export default FavoriteColor;
Example: 2 Instead use of multiple state use
state object and Update
data of State Object
import './App.css'
import { useState } from 'react';
function App() {
const [car, setCar] = useState({
brand: "Ferrari",
model: "Roma",
year: "2023",
color: "red"
}) ;
const changeColor = () => {
//setColor({color:”red”})//replace
whole object which is not right way
setCar((prev) => {
return {…prev, color:”blue”}
//instead of prev we can write any
name
//we can preserve whole object data using …prev
and then we can add new value to state object
})
}
return (
<>
<h1>My {car.brand}</h1>
<h2>It is a {car.color} {car.model}
from {car.year)</h2>
<button
onClick={changeColor}>Blue</button>
</>
)
}
export default App
Example : 3 Increase counter with useState prev value
import './App.css';
function App() {
const [count, setCount] =
useState(0);
const increaseCount = () => {
setCount(count+1) //increase counter
by 1
//but if you increase counter by 4 like below
then also it will increase by 1 in UI- refer below snapshot-1.
setCount(count+1)//take initial
value 0 +1 =1
setCount(count+1) //take initial
value 0 +1 =1
setCount(count+1) //take initial
value 0 +1 =1
setCount(count+1) //take initial
value 0 +1 =1
//To update counter by 4 in UI side need to use
prev value like below refer below snapshot-2
setCount((prev)=>{prev+1}))//take
initial value 0 +1 = 1
setCount((prev)=>{prev+1}))//take
prev value 1 +1 = 2
setCount((prev)=>{prev+1}))//take
prev value 2 +1 = 3
setCount((prev)=>{prev+1}))//take
prev value 3 +1 = 4
//you can also use count instead of
prev like below
setCount((count)=>{count
+1}))//take count initial value 0 +1 = 1
setCount((count)=>{count
+1}))//take count prev value 1 +1 = 2
setCount((count)=>{count
+1}))//take count prev value 2 +1 = 3
setCount((count)=>{count
+1}))//take count prev value 3 +1 = 4
}
return (
<>
<h1>Count : 0</h1>
<button onClick={increaseCount}>Increase</button>
</>
)
}
export default App
No comments:
Post a Comment