xxxxxxxxxx
import { 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 {useState} from 'react'
const [count, setCount] = useState(0);
console.log(count) // returns 0
setCount(1)
console.log(count) // returns 1
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';
function Counter() {
// Define the state variable "count" and the state update function "setCount"
const [count, setCount] = useState(0);
const increment = () => {
// Update the "count" state by increasing its value by 1
setCount(count + 1);
};
const decrement = () => {
// Update the "count" state by decreasing its value by 1
setCount(count - 1);
};
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
xxxxxxxxxx
import { useState } from "react";
const App = () => {
const [name, setName] = useState("imran");
const handleInputChange = (event) => {
setName(event.target.value);
};
const handleRename = () => {
// Perform any additional logic if needed
// For now, we'll just update the name directly
// based on the input value
setName(name);
};
return (
<div>
<h1>{name}</h1>
<input type="text" value={name} onChange={handleInputChange} />
<button onClick={handleRename}>Rename</button>
</div>
);
};
export default App;
xxxxxxxxxx
var fruitStateVariable = useState('banana'); // Returns a pair
var fruit = fruitStateVariable[0]; // First item in a pair
var setFruit = fruitStateVariable[1]; // Second item in a pair
xxxxxxxxxx
function handleOrangeClick() {
// Similar to this.setState({ fruit: 'orange' })
setFruit('orange');
}
xxxxxxxxxx
The initial value will be assigned only on the initial render (if it’s a function, it will be executed only on the initial render).