My Docs
My BlogPython Data StructuresRepoFamily-Promise-Docs
Web-Dev-Hub-Docs
Web-Dev-Hub-Docs
  • Home
  • Navigation
  • Tools
    • Tools
      • Docker
      • G-Cloud & Firebase
      • Heroku
      • Dropbox
      • Email
      • Tools
      • DuckDuckGo
      • Elasticsearch
      • CodeSandbox
      • Product Hunt
      • Raycast
      • Elasticsearch
      • Tools
      • Showcase
        • Utilities
        • Continued
          • Page 3:
    • Downloads
    • REPL.IT Compilations
      • Part 2
    • Past Notes
      • Command Line Reference
    • Git
    • JavaScript
      • Interview Problems
      • General JavaScript Notes
      • jQuery
      • NodeJS
        • Node argv
        • NPM
        • Express
          • ExpressJS Overview
          • Sequelize
      • Regex
      • React
        • React Examples:
        • Redux
        • Redux Docs
          • Redux Resources
        • React Notes
    • My Bash Commands
    • Learning
  • Programming Languages
    • Programming Languages
      • File System
      • Basics
      • PSEUDO Programing Languages
        • HTML
      • CSS
      • List Of Programming Languages By Type
      • Tools-Of-The-Trade
        • Linux
        • Docker
      • Git
      • Python
        • Pydrive:
        • Practice
        • Pipenv
        • Untitled
      • Bash
        • SED
      • CHEATSHEETS
      • Java
      • Html
      • Markdown
      • CSS
      • SCSS
      • C & C++
      • Ruby
      • SQL
        • PostgreSQL
      • Jest
      • JavaScript
      • Typescript
      • C++
      • Babel
    • What is a Programming Language?
  • Python
    • Python
      • Python General Notes
      • Python Quiz
      • Python Cheat Sheet
      • Python Snippets
      • Python at length
    • Install PIP
  • JavaScript
    • JavaScript
      • Jquery
      • Page 16
    • Writing Files
    • JS-Leetcode
  • Web Development Frameworks & Libraries
    • GRAPHQL
    • React
    • Jquery
      • Prac
    • GATSBY
      • Untitled
      • Building with Components
      • Plugins, Themes, & Starters
      • GraphQL Concepts
  • Productivity
    • Productivity
      • Awesome Productivity Tools for Back-to-School
  • Misc
    • Misc
      • Experiments
  • GitGateway
    • Links
    • Bookmarks
  • Websites
    • Websites
    • Not My Websites:
    • Articles
  • Backend
    • Backend
  • Networking
    • Networks
  • Resources
    • Web Dev Tutorials
      • Node
        • API Security
    • Resources
    • Video Resources
  • General Knowledge
    • General Knowledge
    • Glossary
    • Knowledge Bank
  • Finance
    • Finance
    • Finance Reference
    • Financial Trends
  • Science & Tech (Innovation)
    • Science & Tech
    • Articles
  • Reading
    • Reading
  • Social Media & Trends
    • Trends In Web Dev
    • Analytics
    • FB-Dev-Open Source
      • Content Publishing
    • IG-API
  • Docs
    • Docs
      • NodeJS
        • installed it?
        • Timers in Node.js and beyond
        • Node.js web app
        • Overview of Blocking vs Non-Blocking
        • Don't Block the Event Loop (or the Worker Pool)
  • Code Editors & Tools
    • Vscode
      • Vscode Docs
      • How To Speed Up Vscode
  • Cool Stuff
    • Cool Observable Notebooks
  • Server-Side
    • GraphQL
      • Intro
    • Rest VS GraphQl
    • REST-API
    • Public APIs
  • WEB_DEV_TOOLS
    • Web Dev Tools
    • Cloudinary
    • Postman
      • Creating an API
      • Trouble Shooting Postman
    • Netlify
      • Facebook Graph API
      • Pandoc
      • Graph API
      • Troubleshooting
      • Examples
      • HTTPS (SSL)
      • Open Authoring
      • Netlify CMS
      • Git Gateway
  • DS_ALGOS_BRAINTEASERS
    • A Quick Guide to Big-O Notation, Memoization, Tabulation, and Sorting Algorithms by Example
  • Free-Stuff
    • Free Stuff
  • Job-Search
    • Job Search
    • Outreach
  • General Comp Sci
    • Principles behind the Agile Manifesto
  • Blockchain & Crypto
    • Blockchain Basics
      • Basics:
  • Data Structures & Interviewing
    • Data Structures
    • Computational Complexity
  • REACT_REVISITED
    • Modern React with Redux
      • React-Projects
  • WEBDEV-Bootcamp-Notes
    • 🏫Lambda
      • 1.1 - User Interface and Git
      • Page 2
      • Page 1
      • Page 3
      • Page 4
      • Page 5
      • Page 6
      • Page 7
      • Page 8
      • Page 9
      • Page 10
      • Page 11
      • Page 12
      • Page 13
      • Page 14
      • Page 15
      • CS-Python-Notes
        • Python
  • Unsorted-Notes
    • Compiled-Random-Notes
    • Testing:
      • Configure Jest for Testing JavaScript Applications
      • install, configure, and script Cypress for JavaScript web applications
      • Test React Components with Jest and `react-testing-library`
      • Use testing library to evaluate any framework...
  • Medium-articles
    • My Articles
      • Python For JS Developers
      • JavaScript Programmer
      • Awesome Web Development Youtube Video Archive
      • Bash Commands That Save Me Time and Frustration
      • Git-Tricks
      • scrap
      • Medium Article
      • Everything You Need To Know About Relational Databases, SQL, PostgreSQL and Sequelize To Build…
      • Machine Learner
      • Here’s the expanded list:
      • The Complete JavaScript Reference Guide
      • This is really cool!
      • Web Development Interview Part 3💻
      • Mutability And Reference VS Privative Types in JavaScript
      • React
      • Super Simple Intro To HTML
      • Introduction to React for Complete Beginners
      • Web Developer Resource List Part 2
      • Front End Interview Questions Part 2
      • A List Of Tools For Improvement
      • Github Repositories That Will Teach You How To Code For Free!
      • Libraries
      • Machine Learner
      • Here’s the expanded list:
      • The Complete JavaScript Reference Guide
  • 🖲️AI
    • Pytorch
      • Documentation
  • 🎙️Audio
    • Audio
Powered by GitBook
On this page
  • Getting Started with Redux
  • Installation​
  • Basic Example​
  • Learn Redux​
  • Help and Discussion​
  • Should You Use Redux?​

Was this helpful?

  1. REACT_REVISITED

Modern React with Redux

Master React and Redux with React Router, Webpack, and Create-React-App.

PreviousComputational ComplexityNextReact-Projects

Last updated 3 years ago

Was this helpful?

Getting Started with Redux

Redux is a predictable state container for JavaScript apps.

It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as .

You can use Redux together with , or with any other view library. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.

Installation

Redux Toolkit

is our official recommended approach for writing Redux logic. It wraps around the Redux core, and contains packages and functions that we think are essential for building a Redux app. Redux Toolkit builds in our suggested best practices, simplifies most Redux tasks, prevents common mistakes, and makes it easier to write Redux applications.

RTK includes utilities that help simplify many common use cases, including , , and even .

Whether you're a brand new Redux user setting up your first project, or an experienced user who wants to simplify an existing application, can help you make your Redux code better.

Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:

# NPMnpm install @reduxjs/toolkit# Yarnyarn add @reduxjs/toolkit

Copy

Create a React Redux App

The recommended way to start new apps with React and Redux is by using the or for , which takes advantage of and React Redux's integration with React components.

# Redux + Plain JS templatenpx create-react-app my-app --template redux# Redux + TypeScript templatenpx create-react-app my-app --template redux-typescript

Copy

The Redux core library is available as a package on NPM for use with a module bundler or in a Node application:

# NPMnpm install redux# Yarnyarn add redux

Copy

The whole global state of your app is stored in an object tree inside a single store. The only way to change the state tree is to create an action, an object describing what happened, and dispatch it to the store. To specify how state gets updated in response to an action, you write pure reducer functions that calculate a new state based on the old state and the action.

import { createStore } from 'redux'/** * This is a reducer - a function that takes a current state value and an * action object describing "what happened", and returns a new state value. * A reducer's function signature is: (state, action) => newState * * The Redux state should contain only plain JS objects, arrays, and primitives. * The root state value is usually an object.  It's important that you should * not mutate the state object, but return a new object if the state changes. * * You can use any conditional logic you want in a reducer. In this example, * we use a switch statement, but it's not required. */function counterReducer(state = { value: 0 }, action) {  switch (action.type) {    case 'counter/incremented':      return { value: state.value + 1 }    case 'counter/decremented':      return { value: state.value - 1 }    default:      return state  }}// Create a Redux store holding the state of your app.// Its API is { subscribe, dispatch, getState }.let store = createStore(counterReducer)// You can use subscribe() to update the UI in response to state changes.// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.// There may be additional use cases where it's helpful to subscribe as well.store.subscribe(() => console.log(store.getState()))// The only way to mutate the internal state is to dispatch an action.// The actions can be serialized, logged or stored and later replayed.store.dispatch({ type: 'counter/incremented' })// {value: 1}store.dispatch({ type: 'counter/incremented' })// {value: 2}store.dispatch({ type: 'counter/decremented' })// {value: 1}

Copy

Instead of mutating the state directly, you specify the mutations you want to happen with plain objects called actions. Then you write a special function called a reducer to decide how every action transforms the entire application's state.

In a typical Redux app, there is just a single store with a single root reducing function. As your app grows, you split the root reducer into smaller reducers independently operating on the different parts of the state tree. This is exactly like how there is just one root component in a React app, but it is composed out of many small components.

This architecture might seem like a lot for a counter app, but the beauty of this pattern is how well it scales to large and complex apps. It also enables very powerful developer tools, because it is possible to trace every mutation to the action that caused it. You can record user sessions and reproduce them just by replaying every action.

Redux Toolkit simplifies the process of writing Redux logic and setting up the store. With Redux Toolkit, that same logic looks like:

import { createSlice, configureStore } from '@reduxjs/toolkit'const counterSlice = createSlice({  name: 'counter',  initialState: {    value: 0  },  reducers: {    incremented: state => {      // Redux Toolkit allows us to write "mutating" logic in reducers. It      // doesn't actually mutate the state because it uses the Immer library,      // which detects changes to a "draft state" and produces a brand new      // immutable state based off those changes      state.value += 1    },    decremented: state => {      state.value -= 1    }  }})export const { incremented, decremented } = counterSlice.actionsconst store = configureStore({  reducer: counterSlice.reducer})// Can still subscribe to the storestore.subscribe(() => console.log(store.getState()))// Still pass action objects to `dispatch`, but they're created for usstore.dispatch(incremented())// {value: 1}store.dispatch(incremented())// {value: 2}store.dispatch(decremented())// {value: 1}

Copy

Redux Toolkit allows us to write shorter logic that's easier to read, while still following the same Redux behavior and data flow.

We have a variety of resources available to help you learn Redux.

Redux maintainer Mark Erikson appeared on the "Learn with Jason" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with Typescript, as well as the new RTK Query data fetching APIs.

Redux is a valuable tool for organizing your state, but you should also consider whether it's appropriate for your situation. Don't use Redux just because someone said you should - take some time to understand the potential benefits and tradeoffs of using it.

Here are some suggestions on when it makes sense to use Redux:

  • You have reasonable amounts of data changing over time

  • You need a single source of truth for your state

  • You find that keeping all your state in a top-level component is no longer sufficient

For more thoughts on how Redux is meant to be used, see:

Redux Core

It is also available as a precompiled UMD package that defines a window.Redux global variable. The UMD package can be used as a directly.

For more details, see the page.

Basic Example

Redux Toolkit Example

Learn Redux

Redux Essentials Tutorial

The is a "top-down" tutorial that teaches "how to use Redux the right way", using our latest recommended APIs and best practices. We recommend starting there.

Redux Fundamentals Tutorial

The is a "bottom-up" tutorial that teaches "how Redux works" from first principles and without any abstractions, and why standard Redux usage patterns exist.

Learn Modern Redux Livestream

See for a transcript and links to the example app source.

Additional Tutorials

The Redux repository contains several example projects demonstrating various aspects of how to use Redux. Almost all examples have a corresponding CodeSandbox sandbox. This is an interactive version of the code that you can play with online. See the complete list of examples in the .

Redux creator Dan Abramov's **free ** and video courses on Egghead.io

Redux maintainer Mark Erikson's and

Dave Ceddia's post

Other Resources

The answers many common questions about how to use Redux, and the has information on handling derived data, testing, structuring reducer logic, and reducing boilerplate.

Redux maintainer Mark Erikson's demonstrates real-world intermediate and advanced techniques for working with React and Redux (also available as ).

The has categorized articles on working with , , , and more.

Our community has created thousands of Redux-related libraries, addons, and tools. The lists our recommendations, and there's a complete listing available in the .

Help and Discussion

The of the is our official resource for all questions related to learning and using Redux. Reactiflux is a great place to hang out, ask questions, and learn - come join us!

You can also ask questions on using the .

If you have a bug report or need to leave other feedback,

Should You Use Redux?

live code editing combined with a time traveling debugger
React
​
​
Redux Toolkit
store setup
creating reducers and writing immutable update logic
creating entire "slices" of state at once
Redux Toolkit
​
official Redux+JS template
Redux+TS template
Create React App
Redux Toolkit
​
<script> tag
Installation
​
​
​
​
Redux Essentials tutorial
​
Redux Fundamentals tutorial
​
the "Learn Modern Redux" show notes page
​
Examples page
"Getting Started with Redux" video series
Building React Applications with Idiomatic Redux
"Redux Fundamentals" conference talk
"Redux Fundamentals" workshop slides
A Complete React Redux Tutorial for Beginners
​
Redux FAQ
"Using Redux" docs section
"Practical Redux" tutorial series
an interactive course on Educative.io
React/Redux links list
reducers and selectors
managing side effects
Redux architecture and best practices
"Ecosystem" docs page
Redux addons catalog
​
#redux channel
Reactiflux Discord community
Stack Overflow
#redux tag
please file an issue on the Github repo
​
Redux FAQ: When should I use Redux?
You Might Not Need Redux
The Tao of Redux, Part 1 - Implementation and Intent
The Tao of Redux, Part 2 - Practice and Philosophy
Redux FAQ