Managing React State
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
function Counter() {
const [count, setCount] = React.useState(0)
const increment = () => setCount(c => c + 1)
return <button onClick={increment}>{count}</button>
}class Counter extends React.Component {
state = {count: 0}
/*
Another way is
constructor(props){
super(props)
this.state = { count : 0 }
} */
increment = () => this.setState(({count}) => ({count: count + 1}))
render() {
return <button onClick={this.increment}>{this.state.count}</button>
}
}import MyContext from './MyContext';
class MyProvider extends Component {
state = {
cars: {
car001: { name: 'Honda', price: 100 }
}
};
render() {
return (
<MyContext.Provider
value={{
cars: this.state.cars,
incrementPrice: selectedID => {
},
decrementPrice: selectedID => {
}
}}>
{this.props.children}
</MyContext.Provider>
);
}
}import { createStore } from 'redux'
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
let store = createStore(counter)
store.subscribe(() => console.log(store.getState()))
store.dispatch({ type: 'INCREMENT' })
store.dispatch({ type: 'INCREMENT' })
store.dispatch({ type: 'DECREMENT' })