Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useReducer } from "react";
- // initial state
- const initialState = {counter: 0};
- // action type
- const INC = 'INCREMENT';
- const DEC = 'DECREMENT';
- // action creator inc
- function incActionCreator() {
- return {
- type: INC,
- }
- }
- // action creator dec
- function decActionCreator() {
- return {
- type: DEC,
- }
- }
- // action reducer
- function hooksReducer(state, action) {
- switch(action.type) {
- case 'INCREMENT':
- return {
- ...state,
- counter: state.counter++
- }
- case 'DECREMENT':
- return {
- ...state,
- counter: state.counter--
- }
- default:
- return state;
- }
- }
- // app component
- function App () {
- // useReducer is very similar to the store in Redux
- const [stateAction, setDispatchAction] = useReducer(hooksReducer, initialState);
- const incClick = (e) => setDispatchAction(incActionCreator())
- const decClick = (e) => setDispatchAction(decActionCreator())
- return (
- <>
- <button onClick={incClick}>Incerement</button>
- <button onClick={decClick}>Decrement</button>
- <h4>Counter: {stateAction.counter}</h4>
- </>
- );
- }
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement