setstate hook code example
Example 1: react usestate
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>
);
}
Example 2: how to set value in array react hook usestate
const[array,setArray]= useState([
{id: 1, value: "a string", othervalue: ""},
{id: 2, value: "another string", othervalue: ""},
{id: 3, value: "a string", othervalue: ""},
])
const updateItem =(id, whichvalue, newvalue)=> {
var index = array.findIndex(x=> x.id === id);
let g = array[index]
g[whichvalue] = newvalue
if (index === -1){
console.log('no match')
}
else
setArray([
...array.slice(0,index),
g,
...array.slice(index+1)
]
);
}
onPress={()=>updateItem(2,'value','ewfwf')}
onPress={()=>updateItem(1,'othervalue','ewfwf')}
Example 3: state with react functions
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
Example 4: react hook usestate
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>
</>
);
}
Example 5: usestate react
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>
);
}
Example 6: usestate react
function Example(props) {
return <div />;
}