How to Create Store in Redux: Simple Guide for React
To create a Redux store, use the
configureStore function from @reduxjs/toolkit. Pass your reducers to it, and it returns a store object that holds your app state and lets you dispatch actions.Syntax
The basic syntax to create a Redux store uses configureStore from @reduxjs/toolkit. You provide an object with a reducer property that combines your slice reducers.
- configureStore({ reducer }): Creates the store.
- reducer: An object or function defining how state updates.
javascript
import { configureStore } from '@reduxjs/toolkit'; const store = configureStore({ reducer: { // your reducers here } });
Example
This example shows creating a Redux store with a simple counter slice. It demonstrates how to define a reducer and create the store with it.
javascript
import { configureStore, createSlice } from '@reduxjs/toolkit'; // Define a slice with initial state and reducers const counterSlice = createSlice({ name: 'counter', initialState: 0, reducers: { increment: state => state + 1, decrement: state => state - 1 } }); // Create the Redux store with the counter reducer const store = configureStore({ reducer: { counter: counterSlice.reducer } }); // Dispatch some actions store.dispatch(counterSlice.actions.increment()); store.dispatch(counterSlice.actions.increment()); store.dispatch(counterSlice.actions.decrement()); // Log the current state console.log(store.getState());
Output
{"counter":1}
Common Pitfalls
Common mistakes when creating a Redux store include:
- Not passing a reducer to
configureStore, which causes errors. - Using legacy
createStoreinstead of modernconfigureStore. - Mutating state directly instead of using immutable updates in reducers.
Always use @reduxjs/toolkit for simpler and safer store setup.
javascript
/* Wrong: Missing reducer */ // const store = configureStore({}); // This will error /* Right: Provide reducer */ import { configureStore } from '@reduxjs/toolkit'; const dummyReducer = (state = {}) => state; const store = configureStore({ reducer: { dummy: dummyReducer } });
Quick Reference
Key points to remember when creating a Redux store:
- Use
configureStorefrom@reduxjs/toolkit. - Pass an object with your reducers under the
reducerkey. - Reducers can be combined slices or a single reducer function.
- Dispatch actions to update state and use
store.getState()to read state.
Key Takeaways
Use configureStore from @reduxjs/toolkit to create your Redux store easily.
Always provide a reducer or reducers object when creating the store.
Avoid legacy createStore; prefer configureStore for better defaults and simplicity.
Reducers should update state immutably, often using createSlice helpers.
Dispatch actions to change state and getState() to read current state.