Global State Management with Redux
Show how to set up a Redux store, create actions and reducers, and connect a React component to the Redux store.
import { createStore } from 'redux';
// Define the initial state of our app
const initialState = { counter: 0 };
// Create a reducer function to manage state changes
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, counter: state.counter + 1 };
case 'DECREMENT':
return { ...state, counter: state.counter - 1 };
default:
return state;
}
}
// Create a Redux store with our reducer
const store = createStore(counterReducer);
This code snippet represents the first step in managing global state with Redux. It includes the boilerplate necessary to create a Redux store by defining an initial state, a reducer function to handle actions like 'INCREMENT' or 'DECREMENT', and finally creating the store itself with these configurations.
const incrementAction = { type: 'INCREMENT' };
const decrementAction = { type: 'DECREMENT' };
// Dispatch actions to change the state
store.dispatch(incrementAction);
store.dispatch(decrementAction);
This snippet shows how to create action objects, which are plain JavaScript objects with a 'type' property. It then demonstrates dispatching these actions to the Redux store using store.dispatch(), which triggers the reducer function to update the state based on the action type.
import { useSelector, useDispatch } from 'react-redux';
function CounterComponent() {
const counter = useSelector(state => state.counter);
const dispatch = useDispatch();
return (
<div>
<p>{counter}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
}
This React component utilizes the useSelector and useDispatch hooks from react-redux to interact with the Redux store. useSelector accesses the current state value (`counter` in this case), and useDispatch returns the dispatch function allowing the component to dispatch actions directly, thereby demonstrating connecting a React component to the Redux store and updating the UI in response to state changes.