xxxxxxxxxx
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
xxxxxxxxxx
import React, { useState } from 'react'
import { render } from 'react-dom'
const randomDiceRoll = () => {
return Math.floor(Math.random() * 6) + 1
}
export default function App() {
const [diceRolls, setDiceRolls] = useState([1, 2, 3])
return (
<div>
<button
onClick={() => {
setDiceRolls([diceRolls, randomDiceRoll()])
}}
>
Roll dice
</button>
<ul>
{diceRolls.map((diceRoll, index) => (
<li key={index}>{diceRoll}</li>
))}
</ul>
</div>
)
}
render(<App />, document.querySelector('#app'))
xxxxxxxxxx
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
xxxxxxxxxx
//The useState Hook
//useState is a Hook that lets you
//add React state to function components.
//after a state is changed, the page is rerendered, refecting
//the state change
import React, { useState } from 'react';
function Example() {
// here we declare the state variable count
//and its function or 'setter', setCount
const [count, setCount] = useState(0);
//It returns a pair of values: the current state(count)
//and a function that updates it(setCount)
return (
<div>
<p>You clicked {count} times</p>
//{*setCount is the function that updates the value*}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
xxxxxxxxxx
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
xxxxxxxxxx
import React, { useState } from 'react';
//for boolen(true,false)
const [online,setOnline] = useState(true);
//for data (storing)
const [users,setUsers] = useState([
{id:1,name:"John Doe"},{id:2,name:"Merry"},
]);
return(
<div classsName="container">
<h1 className={`$online ? 'text-success' : 'text-danger' `}> green is online , red is offline </h1>
<button onClick={() => setOnline(!online)}>Switch</button>
</div>