Implementing Redux for State Management
Create a simple Next.js app that uses Redux for state management, showcasing how to setup the store and dispatch actions within components.
import { createStore } from 'redux';
// Action Types
const INCREMENT = 'INCREMENT';
// Action Creators
export const incrementCounter = () => ({
type: INCREMENT,
});
// Initial State
const initialState = {
count: 0,
};
// Reducer
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case INCREMENT:
return {
...state,
count: state.count + 1,
};
default:
return state;
}
};
// Store
export const store = createStore(counterReducer);
This code defines the Redux store, action types, action creators, and the reducer for a simple counter updater in a Next.js application.
import { Provider } from 'react-redux';
import { store } from '../store';
import App from 'next/app';
class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
}
export default MyApp;
This code wraps the entire Next.js application with Redux's 'Provider' component so that all components have access to the Redux store.
import { connect } from 'react-redux';
import { incrementCounter } from '../store';
// A simple component that displays a count and a button to increment it.
const CounterComponent = ({ count, increment }) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
const mapStateToProps = state => ({
count: state.count,
});
const mapDispatchToProps = dispatch => ({
increment: () => dispatch(incrementCounter()),
});
export default connect(mapStateToProps, mapDispatchToProps)(CounterComponent);
This code snippet showcases how to connect a React component to the Redux store to read a piece of state and dispatch an action to update it.