24
loading...
This website collects cookies to deliver better user experience
import { useReducer, Fragment } from "react";
function counterReducer(state, value) {
return state + value;
}
function ReducerCounter() {
const [counter, dispatch] = useReducer(counterReducer, 0);
return (
<Fragment>
<h1>Count: {counter} </h1>
<button onClick={() => dispatch(1)}>Increment</button>
<button onClick={() => dispatch(-1)}>Decrement</button>
</Fragment>
)
}
export default ReducerCounter;
import { useReducer, Fragment } from "react";
function counterReducer(state, action) {
if(action.type === 'INCREMENT') {
return state + 1;
}else if(action.type === 'DECREMENT'){
return state - 1;
}else if(action.type === 'RESET') {
return 0;
}
}
function ReducerCounter() {
const [counter, dispatch] = useReducer(counterReducer, 0);
return (
<Fragment>
<h1>Count: {counter} </h1>
<button onClick={() => dispatch({type: 'INCREMENT'})}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT'})}>Decrement</button>
<button onClick={() => dispatch({ type: 'RESET'})}>Reset</button>
</Fragment>
)
}
export default ReducerCounter;