- configureStore: This function sets up your Redux store with sensible defaults. It automatically configures the Redux DevTools Extension, which is super handy for debugging your application.
- createSlice: This is arguably the most important function. It simplifies the process of creating reducers, actions, and action creators. You define your initial state, reducers, and the slice generates the necessary action creators and action types for you. No more manual action type string definitions! No more manual action creators!
- createAsyncThunk: This utility makes it easy to handle asynchronous operations, like fetching data from an API. It takes care of the loading, success, and error states, reducing the boilerplate code needed for async actions.
-
Create a New React App: Open your terminal and run the following command to create a new React app. Let's call our app
redux-hindi-app:npx create-react-app redux-hindi-app cd redux-hindi-app -
Install Redux Toolkit and React-Redux: Navigate into your project directory and install Redux Toolkit and React-Redux using npm or yarn:
npm install @reduxjs/toolkit react-redux # or yarn add @reduxjs/toolkit react-reduxreact-redux is the library that allows us to connect our React components to the Redux store.
-
Project Structure: Your project directory will look something like this:
redux-hindi-app/ ├── node_modules/ ├── public/ ├── src/ │ ├── components/ │ ├── App.js │ ├── App.css │ ├── index.js │ └── ... ├── package.json └── ... -
Create a Slice File: Inside the
srcdirectory, create a new folder calledfeaturesand a file namedcounterSlice.jsinside it.mkdir src/features touch src/features/counterSlice.js -
Import createSlice: Open
counterSlice.jsand importcreateSlicefrom@reduxjs/toolkit.// src/features/counterSlice.js import { createSlice } from '@reduxjs/toolkit'; -
Define Initial State: Define the initial state for your counter. This is the starting value of your counter.
const initialState = { value: 0, }; -
Create the Slice: Use
createSliceto create the slice. Pass it an object with aname,initialState, andreducersproperty.const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment: (state) => { state.value += 1; }, decrement: (state) => { state.value -= 1; }, incrementByAmount: (state, action) => { state.value += action.payload; }, }, });-
name: The name of the slice (e.g.,'counter'). -
initialState: The initial state of the slice (e.g.,{ value: 0 }).| Read Also : Unearthing The Secrets: Mongol Artifacts Revealed -
reducers: An object where each key is the name of a reducer function, and the value is the reducer function itself.- In the
incrementreducer, we directly modify thestate.value. This is allowed becausecreateSliceuses Immer internally, which makes it safe to mutate the state. - The
decrementreducer reduces the counter. incrementByAmountallows us to increase the counter by any amount we want (usingaction.payload).
- In the
-
-
Export Actions and Reducer: Export the actions and the reducer from the slice.
// Export the actions export const { increment, decrement, incrementByAmount } = counterSlice.actions; // Export the reducer export default counterSlice.reducer;counterSlice.actionsgives you the action creators (e.g.,increment,decrement,incrementByAmount).counterSlice.reduceris the reducer function that you’ll use in your store.
Hey guys! Welcome to a comprehensive guide on Redux Toolkit in React.js, tailored especially for you, my Hindi-speaking friends! We're diving deep into the world of state management, making it super easy and fun. If you've ever felt lost or confused with Redux, trust me, you're not alone. But with Redux Toolkit, things are about to get a whole lot simpler. This article is your one-stop shop, covering everything from the basics to advanced concepts, all explained in a way that's easy to understand. So, grab a cup of chai, get comfy, and let's get started!
What is Redux Toolkit? आसान शब्दों में समझें
Redux Toolkit (RTK) एक ऐसा टूलकिट है जो Redux को इस्तेमाल करने को बहुत आसान बना देता है। पुराने जमाने में, Redux को सेटअप करना थोड़ा मुश्किल था। आपको बहुत सारा boilerplate code लिखना पड़ता था। लेकिन RTK के आने से, ये सब बहुत सरल हो गया है। Imagine it like this: अगर Redux एक बड़ा और जटिल car engine है, तो Redux Toolkit एक ऐसा toolkit है जो आपको उस engine को install करने, use करने और manage करने में मदद करता है, बिना ज्यादा technical details में जाए।
RTK provides pre-configured functions and utilities that drastically reduce the amount of code you need to write. It includes tools for setting up the store, creating reducers, and handling asynchronous actions. Think of it as a set of pre-built components that make working with Redux a breeze. The goal is to make Redux development more efficient, maintainable, and less prone to errors. RTK aims to address the complexities of traditional Redux by providing a standardized and simplified approach to state management. By using RTK, you can focus more on building your application and less on the nitty-gritty details of Redux configuration. This is especially helpful for beginners who might find the initial setup of Redux daunting. With RTK, that initial hurdle is significantly lowered.
The Core Features of Redux Toolkit
Setting up a React.js Project with Redux Toolkit
Alright, let's get our hands dirty and set up a React.js project with Redux Toolkit. This section is going to walk you through the process step-by-step. Don't worry, it's not as scary as it sounds. We'll use create-react-app to get our project up and running quickly. And of course, everything will be explained in Hindi so you can understand it perfectly.
Step-by-Step Installation Guide
Creating Your First Redux Slice
This is where the magic happens! We're going to create our first Redux slice. A slice is a collection of reducer logic and actions for a specific feature of your application. Think of it as a mini-store within your main store. Let’s create a counter slice to understand the concept of createSlice.
Code example with detailed explanations
The Complete Code for counterSlice.js
// src/features/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
value: 0,
};
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});
// Export the actions
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
// Export the reducer
export default counterSlice.reducer;
Setting Up the Redux Store
Now that we have a slice, we need to set up the Redux store. This is where all the state is stored and managed. With Redux Toolkit, setting up the store is very straightforward.
Steps to Set Up Your Store
-
Import configureStore: Open
src/app/store.jsor create one if you don't have it, and importconfigureStorefrom@reduxjs/toolkit.// src/app/store.js import { configureStore } from '@reduxjs/toolkit'; import counterReducer from '../features/counterSlice'; -
Configure the Store: Use
configureStoreto configure your store. Pass it an object with areducerproperty. Thereducerproperty is an object that contains all the reducers from your slices. In our case, we'll include the counter reducer.// src/app/store.js export const store = configureStore({ reducer: { counter: counterReducer, }, });- We import our
counterReducerfromcounterSlice.js. - The
counterkey in thereducerobject is the name we'll use to access the counter state in our components.
- We import our
Complete code for store.js
// src/app/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer,
},
});
Connecting React Components to the Redux Store
Now we have our store and our slice ready. It’s time to connect our React components to the store so they can access and modify the state. We’ll use React-Redux to do this. Remember, React-Redux provides a set of hooks and components to interact with the Redux store.
Steps to Connect Components
-
Wrap Your App with
<Provider>: Opensrc/index.jsand wrap your entire app with the<Provider>component. This component makes the Redux store available to all your child components.// src/index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import { Provider } from 'react-redux'; import { store } from './app/store'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <Provider store={store}> <App /> </Provider> </React.StrictMode> );- We import
Providerfromreact-reduxandstorefrom./app/store. - We pass the
storeas a prop to theProvidercomponent.
- We import
-
Use
useSelectoranduseDispatchin Your Components: Now, let's connect ourApp.jscomponent to the Redux store.// src/App.js import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement, incrementByAmount } from './features/counterSlice'; function App() { const count = useSelector((state) => state.counter.value); const dispatch = useDispatch(); return ( <div className="App"> <h1>Counter: {count}</h1> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> <button onClick={() => dispatch(incrementByAmount(5))}>Increment by 5</button> </div> ); } export default App;- We import
useSelectoranduseDispatchfromreact-redux. useSelectoris used to read data from the Redux store. In this example, we're selectingstate.counter.value.useDispatchis used to dispatch actions. We import the action creators (e.g.,increment,decrement,incrementByAmount) fromcounterSlice.jsand usedispatchto dispatch them.
- We import
Detailed explanations
useSelector: This hook allows us to read data from the Redux store. It takes a function as an argument, which receives the entire Redux state as an argument and returns the specific data you need. For example,useSelector((state) => state.counter.value)reads thevalueproperty from thecounterslice.useDispatch: This hook gives you access to thedispatchfunction, which you can use to dispatch actions to the Redux store. To update the state, you calldispatchwith an action created by your slice's action creators. For instance,dispatch(increment())dispatches theincrementaction.- Actions and Reducers: When you call
dispatch(increment()), this action is dispatched to the Redux store. The store then passes the action to all reducers. The reducer for thecounterslice (defined incounterSlice.js) will handle this action and update the state accordingly.
Handling Asynchronous Operations with createAsyncThunk
Now, let's talk about handling asynchronous operations, like making API calls, using createAsyncThunk. This utility simplifies the process of creating asynchronous actions, reducing boilerplate code.
Implementing Asynchronous Actions
-
Import and Define
createAsyncThunk: ImportcreateAsyncThunkin your slice file. Let's create an async action to fetch a random quote from an API.// src/features/quoteSlice.js import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; // Define the async thunk export const fetchQuote = createAsyncThunk( 'quotes/fetchQuote', async () => { const response = await fetch('https://api.quotable.io/random'); const data = await response.json(); return data; } );createAsyncThunktakes two arguments:- A string that is used as the action type prefix (e.g.,
'quotes/fetchQuote'). - An async function that makes the API call and returns the data.
- A string that is used as the action type prefix (e.g.,
-
Define the initial state:
const initialState = { quote: null, status: 'idle', // 'idle' | 'loading' | 'succeeded' | 'failed' error: null, }; -
Handle the async action in the reducer: Now, let's update our reducer to handle the async action. We need to handle the different states of the async operation: loading, success, and failure.
const quoteSlice = createSlice({ name: 'quotes', initialState, reducers: {}, extraReducers: (builder) => { builder .addCase(fetchQuote.pending, (state) => { state.status = 'loading'; }) .addCase(fetchQuote.fulfilled, (state, action) => { state.status = 'succeeded'; state.quote = action.payload; }) .addCase(fetchQuote.rejected, (state, action) => { state.status = 'failed'; state.error = action.error.message; }); }, });extraReducersis used to handle actions dispatched bycreateAsyncThunk. Thebuilderobject is used to define how to handle the different states (pending, fulfilled, rejected) of the async thunk.pending: The API call is in progress.fulfilled: The API call was successful.rejected: The API call failed.
-
Use the async action in your component:
// src/App.js import React, { useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { fetchQuote } from './features/quoteSlice'; function App() { const dispatch = useDispatch(); const quote = useSelector((state) => state.quotes.quote); const status = useSelector((state) => state.quotes.status); useEffect(() => { dispatch(fetchQuote()); }, [dispatch]); return ( <div className="App"> {status === 'loading' && <p>Loading...</p>} {status === 'succeeded' && <p>Quote: {quote.content}</p>} {status === 'failed' && <p>Error: {error}</p>} </div> ); }
The Complete Code for quoteSlice.js
// src/features/quoteSlice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
// Define the async thunk
export const fetchQuote = createAsyncThunk(
'quotes/fetchQuote',
async () => {
const response = await fetch('https://api.quotable.io/random');
const data = await response.json();
return data;
}
);
const initialState = {
quote: null,
status: 'idle', // 'idle' | 'loading' | 'succeeded' | 'failed'
error: null,
};
const quoteSlice = createSlice({
name: 'quotes',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchQuote.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchQuote.fulfilled, (state, action) => {
state.status = 'succeeded';
state.quote = action.payload;
})
.addCase(fetchQuote.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
});
},
});
export default quoteSlice.reducer;
Best Practices and Tips
Let’s go through some best practices and tips to help you write cleaner and more efficient Redux Toolkit code.
Organized File Structure
- Features Directory: Organize your slices into a
featuresdirectory. - Store Setup: Keep your store setup separate in a file like
src/app/store.js. - Component Structure: Place components in a
componentsdirectory or organize them based on features.
Keep Slices Focused
- Single Responsibility: Each slice should focus on a specific area of your application's state.
- Avoid Overlap: Prevent a slice from being responsible for multiple unrelated state concerns.
Using TypeScript
- Benefits: TypeScript can enhance your Redux Toolkit development by adding type safety, code completion, and refactoring capabilities.
- Integration: You can easily use TypeScript with Redux Toolkit.
Debugging with Redux DevTools
- Install the Extension: Make sure you have the Redux DevTools extension installed in your browser.
- Inspect State: Use DevTools to inspect your application's state, actions, and the time travel debugging feature.
Conclusion
Alright, my friends, we've come to the end of our journey through Redux Toolkit in React.js. I hope this guide, written in Hindi, has helped you understand the key concepts and get started with state management in your React applications. Remember, practice is key! The more you work with Redux Toolkit, the more comfortable you'll become. So keep coding, keep learning, and don't be afraid to experiment. Happy coding, and shukriya for reading!
Lastest News
-
-
Related News
Unearthing The Secrets: Mongol Artifacts Revealed
Jhon Lennon - Oct 22, 2025 49 Views -
Related News
Ironald Williams Library: A Comprehensive Guide
Jhon Lennon - Oct 23, 2025 47 Views -
Related News
UK-India Trade Deal: Latest News & What It Means
Jhon Lennon - Nov 16, 2025 48 Views -
Related News
Hardware & Software: Simple Definitions Explained!
Jhon Lennon - Oct 23, 2025 50 Views -
Related News
Paradise Found: Another You And Me
Jhon Lennon - Oct 23, 2025 34 Views