Redux is a state management tool that is often used in conjunction with React to manage the state of a web application. In order to use Redux in a React application, you first need to set up a Redux store.
What is a Redux store?
The Redux store is an object that holds the state of your application. It is the single source of truth for your application’s state, and it is where you can update and retrieve the state of your application.
Setting up a Redux Store
To set up a Redux store, you will need to install the redux
package from npm. You can do this by running the following command:
npm install redux
Once you have the redux
package installed, you can create a store by importing the createStore
function from the redux
package and calling it with your root reducer.
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
The root reducer is a function that takes in the current state and an action, and returns the next state. You can combine multiple reducers into a single root reducer using the combineReducers
function from the redux
package.
import { combineReducers } from 'redux';
import userReducer from './userReducer';
import postReducer from './postReducer';
const rootReducer = combineReducers({
user: userReducer,
posts: postReducer
});
export default rootReducer;
Creating a Redux Store
To create a Redux store, you need to use the createStore
function from the redux
library. The createStore
function takes two arguments: a reducer function and an initial state.
The reducer function is a pure function that takes in the current state of the application and an action, and it returns the new state of the application. The initial state is the initial value of the state of your application.
Here is an example of how to create a Redux store:
import { createStore } from 'redux';
const initialState = {
count: 0,
};
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + 1,
};
case 'DECREMENT':
return {
count: state.count - 1,
};
default:
return state;
}
}
const store = createStore(reducer);
In this example, we are creating a Redux store that has an initial state of { count: 0 }
and a reducer function that increments or decrements the count
value based on the action type.
Connecting Your Store to Your React Components
To connect your store to your React components, you will need to wrap your root component with the Provider
component from the react-redux
package.
import { Provider } from 'react-redux';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Once your store is connected to your React components, you can access the store and dispatch actions from within your components using the useSelector
and useDispatch
hooks from the react-redux
package.
import { useSelector, useDispatch } from 'react-redux';
function App() {
const user = useSelector(state => state.user);
const dispatch = useDispatch();
const handleSignOut = () => {
dispatch({ type: 'SIGN_OUT' });
};
return (
<div>
<h1>Hello, {user.name}!</h1>
<button onClick={handleSignOut}>Sign Out</button>
</div>
);
}
With these steps, you can set up a Redux store and connect it to your React components. In the next article, we will go over how to create and dispatch actions to update the state in your store.
Exercises
To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.
Write a function that creates a Redux store and initializes it with a state object that contains a property called “counter” with a value of 0.
const createStore = () => {
const store = Redux.createStore((state = {counter: 0}, action) => {
return state;
});
return store;
}
Write a function that dispatches an action to a Redux store and increments the value of the “counter” property by 1.
const incrementCounter = (store) => {
store.dispatch({
type: 'INCREMENT_COUNTER'
});
}
Write a function that retrieves the current state of a Redux store and returns the value of the “counter” property.
const getCounterValue = (store) => {
return store.getState().counter;
}
Write a function that creates a Redux store and initializes it with a state object that contains a property called “todos” with an empty array as its value.
const createStore = () => {
const store = Redux.createStore((state = {todos: []}, action) => {
return state;
});
return store;
}
Write a function that dispatches an action to a Redux store and adds a new todo item to the “todos” array. The todo item should be an object with a “text” property and a “completed” property, both with values that are passed as arguments to the function.
const addTodo = (store, text, completed) => {
store.dispatch({
type: 'ADD_TODO',
text: text,
completed: completed
});
}