Steps to Create a React App with Redux Toolkit
Here is a step-by-step guide to setting up a React app with Redux Toolkit:
1. Create a New React Application
Run the following command to create a new React app:
npx create-react-app appwith_redux
cd appwith_redux
2. Install Redux Toolkit and React-Redux
Install the Redux Toolkit (@reduxjs/toolkit) and React-Redux:
npm install @reduxjs/toolkit react-redux
3. Set Up Redux Store
- Create a redux folder inside the src directory.
- Inside the redux folder, create a file called store.js and define your Redux store:
// src/redux/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
export default store;
4. Create a Slice
- Inside the redux folder, create a file called counterSlice.js:
// src/redux/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
reset: (state) => {
state.value = 0;
},
},
});
export const { increment, decrement, reset } = counterSlice.actions;
export default counterSlice.reducer;
5. Provide the Store to the App
Wrap your application with the Redux Provider to make the store available to all components:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client'; // Use createRoot from react-dom/client
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './App';
// Get the root DOM node
const rootElement = document.getElementById('root');
// Create a root
const root = ReactDOM.createRoot(rootElement);
// Render the app
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
6. Use Redux in a Component
- Open App.js and connect the component to the Redux store using useSelector and useDispatch.
// src/App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, reset } from './redux/counterSlice';
const App = () => {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>Redux Toolkit Counter</h1>
<h2>{count}</h2>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
<button onClick={() => dispatch(reset())}>Reset</button>
</div>
);
};
export default App;
7. Run the Application
Start the development server:
npm start
Visit http://localhost:3000 in your browser to see the application in action.
Keep Learning 🙂