state example in react
Example 1: state with react functions
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: set state
class App extends React.Component {
state = { count: 0 }
handleIncrement = () => {
this.setState({ count: this.state.count + 1 })
}
handleDecrement = () => {
this.setState({ count: this.state.count - 1 })
}
render() {
return (
<div>
<div>
{this.state.count}
</div>
<button onClick={this.handleIncrement}>Increment by 1</button>
<button onClick={this.handleDecrement}>Decrement by 1</button>
</div>
)
}
}
Example 3: setting react state with produce immer
const [filters, setFilters] = useState({});
setFilters((filters) => (
produce(filters, draftFilters => {
if (param[0] === 'page') {
draftFilters.page = parseInt(param[1], 10)
}
if (param[0] === 'per_page') {
draftFilters.perPage = parseInt(param[1], 10)
}
})
));