Convert Figma logo to code with AI

reduxjs logoredux

A JS library for predictable global state management

60,792
15,267
60,792
39

Top Related Projects

227,213

The library for web and native user interfaces.

28,416

🗃️ Centralized State Management for Vue.js.

27,458

Simple, scalable state management.

Reactive State for Angular

8,477

The Redux Framework

30,713

A reactive programming library for JavaScript

Quick Overview

Redux is a predictable state container for JavaScript applications. It helps manage the state of an application in a consistent way, making it easier to develop complex, interactive user interfaces. Redux is often used with React but can be integrated with any JavaScript framework or library.

Pros

  • Predictable state management: Redux maintains a single source of truth for the entire application state
  • Time-travel debugging: Easily track state changes and revert to previous states
  • Middleware support: Extend Redux's capabilities with custom middleware
  • Large ecosystem: Extensive collection of tools, extensions, and community support

Cons

  • Steep learning curve: Requires understanding of functional programming concepts
  • Boilerplate code: Setting up Redux can involve writing a significant amount of initial code
  • Overkill for small projects: May add unnecessary complexity to simple applications
  • Performance concerns: Large applications with frequent state updates may experience performance issues

Code Examples

  1. Creating a Redux store:
import { createStore } from 'redux';

const rootReducer = (state = {}, action) => {
  // Reducer logic here
};

const store = createStore(rootReducer);
  1. Dispatching an action:
const incrementAction = { type: 'INCREMENT' };
store.dispatch(incrementAction);
  1. Subscribing to state changes:
store.subscribe(() => {
  console.log('State updated:', store.getState());
});
  1. Using Redux with React:
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';
import App from './App';

const store = createStore(rootReducer);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Getting Started

To start using Redux in your project:

  1. Install Redux:
npm install redux
  1. Create a reducer:
const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};
  1. Create and use a store:
import { createStore } from 'redux';

const store = createStore(counterReducer);

store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: 'INCREMENT' });

This basic setup allows you to manage state with Redux. For more advanced usage, consider adding middleware, combining reducers, and integrating with React using react-redux.

Competitor Comparisons

227,213

The library for web and native user interfaces.

Pros of React

  • More comprehensive UI library, offering a complete solution for building user interfaces
  • Larger community and ecosystem, with extensive third-party components and tools
  • Virtual DOM for efficient rendering and improved performance

Cons of React

  • Steeper learning curve, especially for beginners
  • Requires additional libraries for state management in complex applications
  • More opinionated about application structure and component design

Code Comparison

React:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(element, document.getElementById('root'));

Redux:

const store = createStore(reducer);

function reducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    default:
      return state;
  }
}

React focuses on component-based UI development, while Redux specializes in state management. React's code demonstrates creating and rendering a component, whereas Redux's code shows setting up a store and defining a reducer for handling state changes. While they serve different purposes, they are often used together in larger applications to manage both UI and application state effectively.

28,416

🗃️ Centralized State Management for Vue.js.

Pros of Vuex

  • Simpler setup and less boilerplate code
  • Tighter integration with Vue.js ecosystem
  • Mutations are synchronous, making state changes more predictable

Cons of Vuex

  • Limited to Vue.js applications, less flexible for other frameworks
  • Smaller community and ecosystem compared to Redux
  • Less suitable for large-scale applications with complex state management needs

Code Comparison

Vuex:

const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state) { state.count++ }
  }
})

Redux:

const reducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'INCREMENT': return { count: state.count + 1 }
    default: return state
  }
}
const store = createStore(reducer)

Both Vuex and Redux are popular state management libraries, but they cater to different ecosystems and have distinct approaches. Vuex is designed specifically for Vue.js applications, offering a more streamlined experience for Vue developers. Redux, on the other hand, is framework-agnostic and provides a more robust solution for complex state management needs across various JavaScript applications.

27,458

Simple, scalable state management.

Pros of MobX

  • Simpler setup and less boilerplate code
  • More intuitive and flexible state management
  • Automatic tracking of observables and reactions

Cons of MobX

  • Less predictable state changes due to mutable state
  • Steeper learning curve for developers used to immutable patterns
  • Potential performance issues with large-scale applications

Code Comparison

MobX:

import { makeObservable, observable, action } from "mobx";

class Counter {
  count = 0;
  constructor() {
    makeObservable(this, {
      count: observable,
      increment: action
    });
  }
  increment() {
    this.count++;
  }
}

Redux:

const initialState = { count: 0 };
const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
};

MobX allows for more direct state mutations and automatic tracking, while Redux enforces immutability and explicit actions. MobX's approach results in less code and a more straightforward implementation, but Redux provides better predictability and easier debugging for complex state management scenarios.

Reactive State for Angular

Pros of NgRx Platform

  • Specifically designed for Angular, providing seamless integration with Angular's ecosystem
  • Includes additional features like Entity State management and Effects for side-effect handling
  • Offers a more opinionated structure, which can lead to more consistent codebases across teams

Cons of NgRx Platform

  • Steeper learning curve due to its complexity and Angular-specific concepts
  • Can be overkill for smaller applications, potentially introducing unnecessary boilerplate
  • Limited to Angular applications, whereas Redux can be used with various frameworks

Code Comparison

NgRx Platform:

@Component({...})
export class MyComponent {
  data$ = this.store.select(selectData);
  constructor(private store: Store) {}
  loadData() {
    this.store.dispatch(loadData());
  }
}

Redux:

const mapStateToProps = state => ({ data: selectData(state) });
const mapDispatchToProps = { loadData };
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

The NgRx example shows Angular-specific syntax and dependency injection, while the Redux example demonstrates its framework-agnostic nature. NgRx leverages RxJS observables, whereas Redux typically uses plain JavaScript objects for state management.

8,477

The Redux Framework

Pros of Rematch

  • Simplified API with less boilerplate code
  • Built-in async actions and effects handling
  • Automatic code splitting for models

Cons of Rematch

  • Smaller community and ecosystem compared to Redux
  • Less documentation and learning resources available
  • Potential performance overhead for larger applications

Code Comparison

Redux:

const INCREMENT = 'INCREMENT'
const incrementAction = () => ({ type: INCREMENT })
const counterReducer = (state = 0, action) => {
  if (action.type === INCREMENT) return state + 1
  return state
}

Rematch:

const counter = {
  state: 0,
  reducers: {
    increment(state) {
      return state + 1
    }
  }
}

Summary

Rematch aims to simplify Redux by reducing boilerplate and providing a more intuitive API. It offers built-in async handling and automatic code splitting, which can be beneficial for many projects. However, Redux has a larger ecosystem, more extensive documentation, and may be more suitable for complex applications. The code comparison demonstrates how Rematch can achieve similar functionality with less code. Ultimately, the choice between Redux and Rematch depends on project requirements, team familiarity, and personal preferences.

30,713

A reactive programming library for JavaScript

Pros of RxJS

  • Powerful for handling complex asynchronous operations and event streams
  • Provides a rich set of operators for transforming and combining observables
  • Better suited for real-time data and event-driven applications

Cons of RxJS

  • Steeper learning curve due to its more complex concepts and operators
  • Can be overkill for simpler state management scenarios
  • Potential for memory leaks if observables are not properly managed

Code Comparison

Redux:

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
};

RxJS:

const increment$ = new Subject();
const count$ = increment$.pipe(
  scan((count) => count + 1, 0)
);
count$.subscribe(count => console.log(count));

Redux is more straightforward for basic state management, while RxJS excels in handling complex data flows and asynchronous operations. Redux uses a centralized store and reducers, making it easier to understand and debug. RxJS, on the other hand, offers more flexibility and power for reactive programming paradigms but requires a deeper understanding of its concepts.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Redux LogoRedux

Redux is a JS library for predictable and maintainable global state management.

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 live code editing combined with a time traveling debugger.

You can use Redux together with React, or with any other view library. The Redux core is tiny (2kB, including dependencies), and has a rich ecosystem of addons.

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.

GitHub Workflow Status npm version npm downloads redux channel on discord

Installation

Create a React Redux App

The recommended way to start new apps with React and Redux Toolkit is by using our official Redux Toolkit + TS template for Vite, or by creating a new Next.js project using Next's with-redux template.

Both of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.

# Vite with our Redux+TS template
# (using the `degit` tool to clone and extract the template)
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app

# Next.js using the `with-redux` template
npx create-next-app --example with-redux my-app

We do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:

npm install @reduxjs/toolkit react-redux

For the Redux core library by itself:

npm install redux

For more details, see the Installation docs page.

Documentation

The Redux core docs are located at https://redux.js.org, and include the full Redux tutorials, as well usage guides on general Redux patterns:

The Redux Toolkit docs are available at https://redux-toolkit.js.org, including API references and usage guides for all of the APIs included in Redux Toolkit.

Learn Redux

Redux Essentials Tutorial

The Redux Essentials tutorial 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 Redux Fundamentals tutorial is a "bottom-up" tutorial that teaches "how Redux works" from first principles and without any abstractions, and why standard Redux usage patterns exist.

Help and Discussion

The #redux channel of the Reactiflux Discord community 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 - please come and join us there!

Before Proceeding Further

Redux is a valuable tool for organizing your state, but you should also consider whether it's appropriate for your situation. Please don't use Redux just because someone said you should - instead, please 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

Yes, these guidelines are subjective and vague, but this is for a good reason. The point at which you should integrate Redux into your application is different for every user and different for every application.

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

Basic Example

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.

Redux Toolkit simplifies the process of writing Redux logic and setting up the store. With Redux Toolkit, the basic app 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.actions

const store = configureStore({
  reducer: counterSlice.reducer
})

// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))

// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}

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

Logo

You can find the official logo on GitHub.

Change Log

This project adheres to Semantic Versioning. Every release, along with the migration instructions, is documented on the GitHub Releases page.

License

MIT

NPM DownloadsLast 30 Days