Counter

File src/index.js

123456789101112131415161718192021222324
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { createStore } from "redux"; import { Provider } from "react-redux" import allReducers from "./reducers/index"; const store = createStore(allReducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); ReactDOM.render( <React.StrictMode> <Provider store={store}> <App /> </Provider> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();

File constants/actionTypes.js

123
export const INCREMENT = 'INCREMENT'; export const DECREMENT = 'DECREMENT'; export const RESET = 'RESET';

File actions/index.js

1234567891011121314151617
import * as types from "../constants/actionTypes"; export const increment = (nr) => { return { type: types.INCREMENT }; }; export const decrement = () => { return { type: types.DECREMENT }; }; export const reset = () => { return { type: types.RESET }; };

File reducers/index.js

1234567
import { combineReducers } from "redux"; import counterReducer from "./counter"; const allReducers = combineReducers({ counter: counterReducer }) export default allReducers;

File reducers/counter.js

123456789101112131415
import * as types from "../constants/actionTypes"; const counterReducer = (state = 0, action) => { switch (action.type) { case types.INCREMENT: return state + 1; case types.DECREMENT: return state - 1; case types.RESET: return 0; default: return state; } } export default counterReducer;

File src/App.js

1234567891011121314151617
import React from 'react'; import { useSelector, useDispatch } from "react-redux"; import { increment, decrement, reset } from "./actions"; const App = () => { const counter = useSelector(state => state.counter); const dispatch = useDispatch(); return ( <div> <p>The counter is {counter}</p> <button onClick={() => dispatch(increment())}>+</button> <button onClick={() => dispatch(decrement())}>-</button> <button onClick={() => dispatch(reset())}>reset</button> </div> ); }; export default App;