Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Redux Store in React Native
Next article icon

How to Create Store in React Redux ?

Last Updated : 18 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

React Redux is a JavaScript library that is used to create and maintain state in React Applications efficiently.

Here React Redux solves the problem by creating a redux store that stores the state and provides methods to use the state inside any component directly or to manipulate the state in a defined manner.

Table of Content

  • Redux Toolkit
  • How to Build Redux Store and Manage Complex State in ReactJS
  • Wrap App with Redux Provider
  • Create Redux Store
  • Create Redux State Slice Reducer
  • Register State Slice in Store
  • Use Redux State in React Component

Redux Toolkit

The Redux toolkit acts as a wrapper around Redux and encapsulates its necessary functions. Redux toolkit is flexible and provides a simple way to make a store for large applications. It follows the SOPE principle which means it is Simple, Opinionated, Powerful, and Effective.

How to Build Redux Store and Manage Complex State in ReactJS

After installing the required modules.

  1. First, create a store using the configureStore method provided by the redux toolkit inside the store.js file. This will be your store but we haven't created reducers.
  2. Now wrap up the whole application using provider which provide the store we created to the application.
  3. Now create slices for the store, use createSlice method from toolkit to create a slice which contains..
    • Name of slice
    • Initial states
    • Reducer which then contains action
  4. Export the reducer and actions
  5. Imort redcuer inside store to register it.
  6. Now its time to use it, select the state inside component using hook and import corresponding actions.
  7. When update required, dispatch the action, this will update the state in store and inside component.

Steps to Create a React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app redux_store

Step 2: After creating your project folder i.e. project_name, move to the folder using the following command:

cd redux_store

Step 3: Install React Redux Module:

npm install @reduxjs/toolkit react-redux

Project Structure:

Screenshot-2024-03-25-231501
project structure

The updated dependencies in package.json file will look like.

"dependencies": {
"@reduxjs/toolkit": "^2.2.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Wrap App with Redux Provider

  • Inside index.js import store from store.js and provider from react redux

Syntax:

<Provider store={store}>
<App />
</Provider>

Create Redux Store

  • Now create a folder store.js and create a store inside it.
  • Also export it, currently it does not include any reducer, we will register the reducers once they created.

Syntax:

export const store = configureStore({
reducer: {
},
})

Create Redux State Slice Reducer

  • Now create a slice, this include reducer and initial state. Also name should be unique. To create slice create another file slice.js.
  • After that export slice reducer and actions

Syntax:

export const counterSlice = createSlice({
name: ' ',
initialState: ,
reducers: {
action_name: (state) => update the state;
},
})

Register State Slice in Store

  • Just import the slice reducer inside store and register it inside the store.

Syntax:

reducer: {
counter: reducer_Name,
}

Use Redux State in React Component

  • Now select the state inside your component using hook:

Syntax:

const state = useSelector( ( state ) => state.slice_name.value )

Now to update the state we have to dispatch the actions we defined earlier

const dispatch = useDispatch( )
dispatch(action_name( ) )

Exaplanation:

  • Below you can see the two button increment and decrement.
  • This button will dispatch the increment and decrement action to the store.
  • Reducer inside store will update the value of counter according to the action. Here counter is a state.
  • And this state available throughout the application and can be manipulated from any component.

Example:

JavaScript
import './App.css'; import {     useSelector,     useDispatch } from 'react-redux' import {     decrement,     increment } from './store/slices/counterSlice'  function App() {      const count = useSelector((state) => state.counter.value)     const dispatch = useDispatch()      return (         <div className="App">             <header className="App-header">                 <p>                     Counter {count}                 </p>                 <button                     onClick={() => dispatch(increment())}>                     Increment                 </button>                 <button                     onClick={() => dispatch(decrement())}>                     Decrement                 </button>             </header>         </div>     ); }  export default App; 
JavaScript
import { configureStore } from '@reduxjs/toolkit' import counterReducer from './slices/counterSlice'  export const store = configureStore({     reducer: {         counter: counterReducer     }, }) 
JavaScript
import { createSlice } from '@reduxjs/toolkit'  export const counterSlice = createSlice({     name: 'counter',     initialState: {         value: 0,     },     reducers: {         increment: (state) => {             state.value += 1         },         decrement: (state) => {             state.value -= 1         }     }, })  export const { increment, decrement } = counterSlice.actions  export default counterSlice.reducer 
JavaScript
import { configureStore } from '@reduxjs/toolkit'  export const store = configureStore({     reducer: {     }, }) 
JavaScript
import React from 'react' import ReactDOM from 'react-dom' import './index.css' import App from './App' import { store } from './store/store' import { Provider } from 'react-redux'  ReactDOM.render(     <Provider store={store}>         <App />     </Provider>,     document.getElementById('root') ) 

Start your application using the following command.

npm start

Output:

gfg41
Output

Next Article
Redux Store in React Native
author
mayankratre10
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Redux

Similar Reads

  • How to store single cache data in ReactJS ?
    Storing Data in a cache is an important task in web applications. We can cache some data into the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested. PrerequisitesReact JSCach
    2 min read
  • How to test React-Redux applications?
    Testing React-Redux applications is crucial to ensure their functionality, reliability, and maintainability. As we know, the React-Redux application involves complex interactions between components and Redux state management, testing helps us to identify and prevent bugs, regressions, and performanc
    10 min read
  • How To Create a Website in ReactJS?
    ReactJS is one of the most popular JavaScript libraries for building user interfaces. It allows you to create dynamic, reusable UI components and efficiently manage state and events. In this article, we'll walk through the steps to create a basic website using ReactJS. PrerequisitesNPM & Node.js
    5 min read
  • How to create a form in React?
    React uses forms to allow users to interact with the web page. In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute and that even
    5 min read
  • Redux Store in React Native
    In this article, we are going to learn about Redux Store. It is the object which holds the state of the application. The store is one of the building blocks of Redux. Redux is a state managing library used in JavaScript apps. It is used to manage the data and the state of the application.   Uses of
    5 min read
  • How to Integrate Redux with React Components ?
    Redux is an open-source JavaScript library for managing and centralizing application state. It helps you to write applications that behave consistently and are easy to test and run in different environments. It can also be understood as the predictable state container for the JavaScript app. It is m
    4 min read
  • How to use React Context with React-Redux ?
    React context with React-Redux is a popular state management library for React applications. Using React context with React-Redux is a powerful way to provide the Redux store to components deep within your component tree without manually passing it down through props. PrerequisitesNode.js and NPMRea
    3 min read
  • Create a To-Do List App using React Redux
    A To-Do list allows users to manage their tasks by adding, removing, and toggling the completion status for each added item. It emphasizes a clean architecture, with Redux state management and React interface rendering. Prerequisites Node.jsReactReact-ReduxApproachCreate a new React project using Cr
    3 min read
  • How to Normalize State in Redux Applications ?
    In Redux applications, efficient state management is essential for scalability and maintainability. Normalization is a technique used to restructure complex state data into a more organized format, improving performance and simplifying state manipulation. This article covers the concept of normaliza
    3 min read
  • What are Action's creators in React Redux?
    In React Redux, action creators are functions that create and return action objects. An action object is a plain JavaScript object that describes a change that should be made to the application's state. Action creators help organize and centralize the logic for creating these action objects. Action
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences