📌 Store
src/store/index.js
import { createStore } from 'redux';
const counterReducer = (state = { counter: 0 }, action) => {
switch (action.type) {
case 'INCREASE':
return { counter: state.counter + 1 };
case 'DECREASE':
return { counter: state.counter - 1 };
default:
return state;
}
};
const store = createStore(counterReducer);
export default store;
📌 Function Component
src/components/Counter.js
import classes from './Counter.module.css';
import { useSelector, useDispatch } from 'react-redux';
const Counter = () => {
const dispatch = useDispatch();
const counter = useSelector((state) => state.counter);
const incrementHandler = () => {
dispatch({ type: 'INCREASE' });
};
const decrementHandler = () => {
dispatch({ type: 'DECREASE' });
};
const toggleCounterHandler = () => {};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
<div className={classes.value}>{counter}</div>
<div>
<button onClick={incrementHandler}>INCREASE BUTTON</button>
<button onClick={decrementHandler}>DECREASE BUTTON</button>
</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
📌 Class Component
src/components/Counter.js
import { Component } from 'react';
import classes from './Counter.module.css';
import { connect } from 'react-redux';
class Counter extends Component {
incrementHandler() {
this.props.increase();
}
decrementHandler() {
this.props.decrease();
}
toggleCounterHandler() {}
render() {
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
<div className={classes.value}>{this.props.counter}</div>
<div>
<button onClick={this.incrementHandler.bind(this)}>
INCREASE BUTTON
</button>
<button onClick={this.decrementHandler.bind(this)}>
DECREASE BUTTON
</button>
</div>
<button onClick={this.toggleCounterHandler}>Toggle Counter</button>
</main>
);
}
}
const mapStateToProps = (state) => {
return {
counter: state.counter,
};
};
const mapDispatchToProps = (dispatch) => {
return {
increase: () => dispatch({ type: 'INCREASE' }),
decrease: () => dispatch({ type: 'DECREASE' }),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter);