react-redux - Official React bindings for Redux Usage with React · Redux

How can I display a modal dialog in Redux that performs asynchronous actions?

I'm building an app that needs to show a confirm dialog in some situations.

Let's say I want to remove something, then I'll dispatch an action like deleteSomething(id) so some reducer will catch that event and will fill the dialog reducer in order to show it.

My doubt comes when this dialog submits.

  • How can this component dispatch the proper action according to the first action dispatched?
  • Should the action creator handle this logic?
  • Can we add actions inside the reducer?


to make it clearer:

deleteThingA(id) => show dialog with Questions => deleteThingARemotely(id)

createThingB(id) => Show dialog with Questions => createThingBRemotely(id)

So I'm trying to reuse the dialog component. Showing/hiding the dialog it's not the problem as this can be easily done in the reducer. What I'm trying to specify is how to dispatch the action from the right side according to the action that starts the flow in the left side.

Source: (StackOverflow)

Understanding React-Redux and mapStateToProps

I'm trying to understand the connect method of react-redux, and the functions it takes as parameters. In particular mapStateToProps.

The way I understand it, the return value of mapStateToProps will be an object derived from state (as it lives in the store), whose keys will be passed to your target component (the component connect is applied to) as props.

This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store.

Is this OK? Is this expected? Or is this what you pros call an anti-pattern?

Source: (StackOverflow)

What is the best way to access redux store outside a react component?

@connect works great when I'm trying to access the store within a react component. But how should I access it in some other bit of code. For eg: let's say I want to use an authorization token for creating my axios instance that can be used globally in my app, what would be the best way to achieve that?

This is my api.js

// tooling modules
import axios from 'axios'

// configuration
const api = axios.create()
api.defaults.baseURL = 'http://localhost:5001/api/v1'
api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here
api.defaults.headers.post['Content-Type'] = 'application/json'

export default api

Now I want to access a data point from my store, here is what that would look like if I was trying to fetch it within a react component using @connect

// connect to store
@connect((store) => {
  return {
    auth: store.auth
export default class App extends Component {
  componentWillMount() {
    // this is how I would get it in my react component
  render() {...}

Any insights or workflow patterns out there?

Source: (StackOverflow)

How to optimize small updates to props of nested component in React + Redux?

Example code: https://github.com/d6u/example-redux-update-nested-props/blob/master/one-connect/index.js

View live demo: http://d6u.github.io/example-redux-update-nested-props/one-connect.html

How to optimize small updates to props of nested component?

I have above components, Repo and RepoList. I want to update the tag of the first repo (Line 14). So I dispatched an UPDATE_TAG action. Before I implemented shouldComponentUpdate, the dispatch takes about 200ms, which is expected since we are wasting lots of time diffing <Repo/>s that haven't changed.

After added shouldComponentUpdate, dispatch takes about 30ms. After production build React.js, the updates only cost at about 17ms. This is much better, but timeline view in Chrome dev console still indicate jank frame (longer than than 16.6ms).

enter image description here

Imagine if we have many updates like this, or <Repo/> is more complicated than current one, we won't be able to maintain 60fps.

My question is, for such small updates to a nested component's props, is there a more efficient and canonical way to update the content? Can I still use Redux?

I got a solution by replacing every tags with an observable inside reducer. Something like

// inside reducer when handling UPDATE_TAG action
// repos[0].tags of state is already replaced with a Rx.BehaviorSubject
get('repos[0].tags', state).onNext([{
  id: 213,
  text: 'Node.js'

Then I subscribe to their values inside Repo component using https://github.com/jayphelps/react-observable-subscribe. This worked great. Every dispatch only costs 5ms even with development build of React.js. But I feel like this is an anti-pattern in Redux.

Update 1

I followed the recommendation in Dan Abramov's answer and normalized my state and updated connect components

The new state shape is:

    repoIds: ['1', '2', '3', ...],
    reposById: {
        '1': {...},
        '2': {...}

I added console.time around ReactDOM.render to time the initial rendering.

However, the performance is worse than before (both initial rendering and updating). (Source: https://github.com/d6u/example-redux-update-nested-props/blob/master/repo-connect/index.js, Live demo: http://d6u.github.io/example-redux-update-nested-props/repo-connect.html)

// With dev build
INITIAL: 520.208ms
DISPATCH: 40.782ms

// With prod build
INITIAL: 138.872ms
DISPATCH: 23.054ms

enter image description here

I think connect on every <Repo/> has lots of overhead.

Update 2

Based on Dan's updated answer, we have to return connect's mapStateToProps arguments return an function instead. You can check out Dan's answer. I also updated the demos.

Below, the performance is much better on my computer. And just for fun, I also added the side effect in reducer approach I talked (source, demo) (seriously don't use it, it's for experiment only).

// in prod build (not average, very small sample)

// one connect at root
INITIAL: 83.789ms
DISPATCH: 17.332ms

// connect at every <Repo/>
INITIAL: 126.557ms
DISPATCH: 22.573ms

// connect at every <Repo/> with memorization
INITIAL: 125.115ms
DISPATCH: 9.784ms

// observables + side effect in reducers (don't use!)
INITIAL: 163.923ms
DISPATCH: 4.383ms

Update 3

Just added react-virtualized example based on "connect at every with memorization"

INITIAL: 31.878ms
DISPATCH: 4.549ms

Source: (StackOverflow)

Passing props to react-redux container component

I have a react-redux container component that is created within a React Native Navigator component. I want to be able to pass the navigator as a prop to this container component so that after a button is pressed inside its presentational component, it can push an object onto the navigator stack.

I want to do this without needing to hand write all the boilerplate code that the react-redux container component gives me (and also not miss out on all the optimisations that react-redux would give me here too).

Example container component code:

const mapStateToProps = (state) => {
    return {
        prop1: state.prop1,
        prop2: state.prop2

const mapDispatchToProps = (dispatch) => {
    return {
        onSearchPressed: (e) => {
            dispatch(submitSearch(navigator)) // This is where I want to use the injected navigator

const SearchViewContainer = connect(

export default SearchViewContainer

And I'd want to be able to call the component like this from within my navigator renderScene function:

<SearchViewContainer navigator={navigator}/>

In the container code above, I'd need to be able to access this passed prop from within the mapDispatchToProps function.

I don't fancy storing the navigator on the redux state object and don't want to pass the prop down to the presentational component.

Is there a way I can pass in a prop to this container component? Alternatively, are there any alternative approaches that I'm overlooking?


Source: (StackOverflow)

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

I am a javascript/redux/react beginner building an small application with redux, react-redux, & react. For some reason when using mapDispatchToProps function in tandem with connect (react-redux binding) I receive a TypeError indicating that dispatch is not a function when I try to execute the resulting prop. When I call dispatch as a prop however (see the setAddr function in the provided code) it works.

I'm curious as to why this is, in the example TODO app in the redux docs the mapDispatchToProps method is setup the same way. When I console.log(dispatch) inside the function it says dispatch is type object. I could continue to use dispatch this way but I would feel better knowing why this is happening before I continue any further with redux. I am using webpack with babel-loaders to compile.

My Code:

import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { setAddresses } from '../actions.js';
import GeoCode from './geoCode.js';
import FlatButton from 'material-ui/lib/flat-button';

const Start = React.createClass({
    propTypes: {
        onSubmit: PropTypes.func.isRequired

    setAddr: function(){
                pickup: this.refs.pickup.state.address,
                dropoff: this.refs.dropoff.state.address


    render: function() {
        return (
                <div className="row">
                    <div className="col-xs-6">
                        <GeoCode ref='pickup' />
                    <div className="col-xs-6">
                        <GeoCode ref='dropoff' />
                <div className="row">
                    <div className="col-xs-6">
                            label='Does Not Work'
                                pickup: this.refs.pickup.state.address,
                                dropoff: this.refs.dropoff.state.address
                    <div className="col-xs-6">

const mapDispatchToProps = (dispatch) => {
    return {
        onSubmit: (data) => {

const StartContainer = connect(mapDispatchToProps)(Start)

export default StartContainer


Source: (StackOverflow)

How to sync Redux state and url query params

I have a web page with a search panel. Search panel has several input fields: id, size, ...

What I want is when user set search values (for example: id=123 and size=45) and press a search button:

  1. searchState in Redux reducer should be updated with new search values (id=123 and size=45)
  2. URL should be changed to "http://mydomain/home?id=123&size=45"

And on the other hand if user changed URL to http://mydomain/home?id=111&size=22 when:

  1. searchState in reducer should be changed with new search values (id=111 and size=22)
  2. UI search panel inputs should be updated with new values (id=111 and size=22)

How to reach with goal? What router should I use (react-router, redux-router, react-router-redux ot other)?

Source: (StackOverflow)

How to get something from the state / store inside a redux-saga function?

How do I access the redux state inside a saga function?

My Problem

I have an application consisting of the following parts:

 User info     |   Current Project

Each part is a different component with it's own reducer, saga, actions and state.

The toolbar has a save button which dispatches a "SAVE_PROJECT" action type. The problem is that I don't want the toolbar to know the project (it has more responsibilities and I just want it to dispatch actions with type).

I have a project related saga which listens to the "SAVE_PROJECT":

export function* saveProjectTask() {
  while(true) {
    yield take(SAVE_PROJECT);
    let project = /* THIS IS THE PROBLEM, I DON'T HAVE THE PROJECT */;
    yield call(fetch, '/api/project', { body: project, method: 'PUT' });
    yield put({type: SAVE_PROJECT_SUCCESS});

I can't get the project from the redux state inside the saga.

I don't think I can listen to the "SAVE_PROJECT" event inside the curren project reducer and then inside the reducer get the project and dispatch a different action with the project.

I really don't want my toolbar to know the entire state tree and send anything related to the action for every action.

How can I pass the state it-self to the saga? Or only the relevant part of the state?

Source: (StackOverflow)

How do I add an element to array in reducer of React native redux?

How do I add elements in my array arr[] of redux state in reducer? I am doing this-

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {

export default function userState(state = initialUserState, action)
    switch (action.type)
        case ADD_ITEM: 
            return { 
                      arr: state.arr.push([action.newItem])

            return state

Source: (StackOverflow)

Where do I fetch initial data from server in a React Redux app?

I've started learning React / Redux and stumbled on something that is probably a very basic question. Below are snippets from my app with some code removed for simplicity sake.

My state is described by an array of sites which is empty by default. Later reducer will have LOAD_SITES action to load a different set of sites whenever user paginates to a different page but for now it's doing nothing. React starts by rendering PublishedSitesPage which then renders PublishedSitesBox which then loops over data and renders individual sites.

What I want to do is have it render everything with the default empty array and meanwhile initiate a "load sites from server" promise and once it resolves, dispatch LOAD_SITES action. What is the best way to make this call? I was thinking about either constructor of PublishedSitesBox or perhaps componentDidMount. But not sure if this would work - my concern is that I'll create an endless loop this way that will keep re-rendering. I guess I could prevent this endless loop in some way by having some other state param along the lines of "haveRequestedInitialData". Another idea I had is to simply make this promise right after doing ReactDOM.render(). What is the best and cleanest way to do this?

export default function sites(state = [], action) {
  switch (action.type) {
      return state;

const publishedSitesPageReducer = combineReducers({

  <Provider store={createStore(publishedSitesPageReducer)}>
    <PublishedSitesPage />


export default function PublishedSitesPage() {
  return (


function mapStateToProps(state) {
  return { sites: state.sites };

const PublishedSitesBox = connect(mapStateToProps)(({sites}) => {
  // render sites

Source: (StackOverflow)

Redux-form handleSubmit: How to access store state?

In a redux-form handleSubmit function, which makes an Ajax call, some properties from the Redux state are needed in the Ajax (e.g. user ID).

This would be easy enough if I wanted to define handleSubmit in the form's component: Just call mapStateToProps to pass in whatever I need, and read it from this.props in my handleSubmit.

However, like a good React-Redux developer I write separate view components and containers, so my view components can be simple with little or no behavior. Therefore, I want to define handleSubmit in my container.

Again, simple - redux-form is set up to do that. Define an onSubmit in mapDispatchToProps, and the form will call it automatically.

Except, oh wait, in mapDispatchToProps there's no way to access redux state.

Okay, no problem, I'll just pass the props I need into handleSubmit along with the form values.

Hmm, wait, it is impossible to pass any data into handleSubmit using this mechanism! You get one parameter, values, and there's no way to add another parameter.

This leaves the following unattractive alternatives (of which I can verify that 1 and 2 work):

1 Define a submit handler in the form component, and from there call my own custom submit handler function passed in from mapDispatchToProps. This is okay, but requires my component to know some props from the redux state that aren't required to display the form. (This issue is not unique to redux-form.)

  const { mySubmitHandler, user} = this.props;
  mySubmitHandler(values, user);

<form onSubmit={ handleSubmit(this.dumbSubmit.bind(this)) }>

Or, more concisely, this can all be combined into an arrow function:

<form onSubmit={ handleSubmit((values)=>{mySubmitHandler(values, this.props.user);}

Then to make this handler completely agnostic, it could just pass the entire this.props back to the custom handler:

<form onSubmit={ handleSubmit((values)=>{mySubmitHandler(values, this.props);}

2 Define onSubmit in mergeProps instead of mapDispatchToProps, so it has access to stateProps. Dan Abramov recommends against using mergeProps (for performance reasons), so this seems suboptimal.

  function mergeProps(stateProps, dispatchProps, ownProps) {
  const { user } = stateProps.authReducer;
  const { dispatch } = dispatchProps;
  return {
     onSubmit: (values) => {
       const { name, description } = values;
       const thing = new Thing(name, description, []);
       dispatch(createNewThing(thing, user.id));

3 Copy the state properties into redux-form fields which are not mapped to any input controls in the form component. This will ensure they are accessible in the values parameter passed back to handleSubmit. This seems like kind of a hack.

There's got to be a better way!

Is there a better way?

Source: (StackOverflow)

Can react-redux connect() -ed containers implement lifecyle methods like componentDidMount?

I've come across a repeated pattern in my react-redux site: A component displays data from a web api, and it should be populated on load, automatically, without any user interaction.

I want to initiate the async fetch from a container component, but as far as I can tell the only way to do it is from a lifecycle event in a display component. This seems to make it impossible to put all the logic in the container and only use dumb stateless functional components for display.

This means I can't use a stateless functional component for any component that needs async data. That doesn't seem right.

It seems like the "right" way to do this would be to somehow initiate async calls from the container. Then when the call returned, the state would be updated and the container would get the new state and would in turn pass those to its stateless component via mapStateToProps().

Making async calls in mapStateToProps and mapDispatchToProps (I mean actually calling the async function, as opposed to returning it as a property) doesn't make sense.

So what I've ended up doing is putting the async call(s) in a refreshData() function exposed by mapDispatchToProps(), then calling it from two or more of the React lifecycle methods: componentDidMount and componentWillReceiveProps.

Is there a clean way to update the redux store state without putting lifecycle method calls in every component that needs async data?

Should I be making these calls higher up the component heierarchy (thereby reducing the scope of this issue, since only "top-level" components would need to listen to lifecycle events)?


Just so there's no confusion what I mean by a connect()ed container component, here's a very simple example:

import React from 'react';
import { connect } from 'react-redux';
import {action} from './actions.js';

import MyDumbComponent from './myDumbComponent.jsx';

function mapStateToProps(state)
  return { something: state.xxxreducer.something  };

function mapDispatchToProps(dispatch)
  return { 
       doAction: ()=>{dispatch(action())}

const MyDumbComponentContainer = connect(

// Uh... how can I hook into to componentDidMount()? This isn't 
// a normal React class.

export default MyDumbComponentContainer;

Source: (StackOverflow)

Access State inside of mapDispatchToProps method

I have written a container component using redux and my implementation for mapDispathToProps looks like this

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        onChange: (newValue) => {
            dispatch(updateAttributeSelection('genre', newValue));
            dispatch(getTableData(newValue, ownProps.currentYear));

The problem is that in order to getTableData i need the state of some other components. How can I get access to the state object in this method?

Source: (StackOverflow)

Warning: flattenChildren(...): Encountered two children with the same key / Child keys must be unique

Yesterday I added react-router-dom to my project and now when I leave and come back to my Sky element in my nav, it reloads the sky and I get

Warning: flattenChildren(...): Encountered two children with the same key, element-id-50. Child keys must be unique; when two children share a key, only the first child will be used.

(the number 50 used above is just an example, it throws this error ~40 times each time all with different ids)

The problem seems to stem from here in my sky.js file:

componentWillMount() {

    this.setState({loadedSky: true, loadedElements: true});

Since each time I'm going to another screen, this component is unmounting and then re-mounting when I come back.

When receiveSkySetup is finished, the render function in sky.js creates a bunch of divs called Sectors and each Sector creates a few divs called Slots.

Then inside of Slot.render I have:

return connectDropTarget(
            <div className={showOutline ? 'slot showOutline' : 'slot'} style={style} onClick={interactable ? this.handleClick : null}>
                        .map(e => (
                                transformElement={false} />

The key element in the SkyElement call above is what's throwing the 40+ errors on each mounting.

Happy to provide more code if needed.

Any help would be hugely helpful. Thanks!

Edit: Console logging elements

Digging in a bit more, the items are doubling in my store.

So, on the 2nd render of the sky tab, the full list of element ids is ["0", "1", "2", "3", "4", "5", "6", "7", "17", "18", "19", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "77", "78", "0", "1", "2", "3", "4", "5", "6", "7", "17", "18", "19", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "77", "78"]

On the 3rd render, elements 0-78 (the ids that apply from the array above) will be added again to the array

In Slot.js

const mapStateToProps = ({elements}, ownProps) => {
    return {
        elements: getElementsBySlotId(elements, ownProps.id),

elements here will be n times the number of loads that Sky has done.

In sky.js

const mapStateToProps = ({sky, elements}) => {
    return {
        sectors: getSky(sky).sectors,
        elements: getElementsByKeyName(elements, 'visibleElements'),
        unplacedElements: getElementsByKeyName(elements, 'unplacedElements'),

Printing elements.length I see that they double here too. Slot.js is pulling from the same store, so that makes sense

In my elements/reducer.js

case 'receiveAllElements':
        const visibleElements = {};
        const unplacedElements = {};

        const elements = action.elements.reduce((result, index) => {
            result[`${index.id}`] = index;
            return result;
        }, {});

        const keys = Object.keys(elements);
        for (const key of keys) {
            const e = elements[key];

            if (e.sectorId === null) {
                unplacedElements[key] = e;
            } else {
                visibleElements[key] = e;

        const visibleIds = Object.keys(visibleElements);
        const unplacedIds = Object.keys(unplacedElements);
        console.log(unplacedIds); // logging these, the numbers are consistent and don't double, triple etc with each load

        return {
            elementsMap: {
            visibleElements: [...state.visibleElements, ...visibleIds],
            unplacedElements: [...state.unplacedElements, ...unplacedIds],

Maybe something in there is causing the count to double?

Source: (StackOverflow)

Redux-Form initial values from

I'm trying to fill the profile form with data from API. Unfortunately redux-form doesn't want to cooperate with me in this case. For some reason fields stays empty whatever I do.

Setting the fixed values instead of values passed from reducer work well for some reason.

Maybe this is because I'm using redux-promise for API calls inside the action creators? How can I live with it and get rid of this. Here is my form component.

import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import { connect } from 'react-redux';
import { fetchRoleList, fetchUserData } from '../actions';

class UserEdit extends Component {

    componentWillMount() {

    handleEditProfileFormSubmit(formProps) {

    getRoleOptions(selected_id) {
        if (!this.props.profile) {
            return <option>No data</option>;

        return this.props.profile.roles.map(role => {
            return <option key={role.role_id} value={role.role_id}>{role.name}</option>;

    renderField(props) {
        const { input, placeholder, label, value, type, meta: { touched, error } } = props;
        return (
        <fieldset className={`form-group ${ (touched && error) ? 'has-error' : '' }`}>
            <input className="form-control" {...input} type={type} placeholder={placeholder} />
            {touched && error && <div className="error">{error}</div>}

    renderSelect({ input, placeholder, options, label, type, meta: { touched, error } }) {
        return (
        <fieldset className={`form-group ${ (touched && error) ? 'has-error' : '' }`}>
            <select className="form-control" {...input}>
            {touched && error && <div className="error">{error}</div>}

    render() {
        const { handleSubmit } = this.props;

        const user = this.props.profile.user;

        return (
        <div> {user ? user.email : ''}
            <form onSubmit={handleSubmit(this.handleEditProfileFormSubmit.bind(this))}>
                <Field name="email" label="Email:" component={this.renderField} type="text" placeholder="email@gmail.com" className="form-control"/>
                <Field name="name" label="Name:"  component={this.renderField} type="text" placeholder="John Doe" className="form-control"/>
                <Field name="role" label="Role:" component={this.renderSelect} type="select" className="form-control" options={this.getRoleOptions()}/>
                <button action="submit" className="btn btn-primary">Edit user</button>

                <Field name="password" label="Password:" component={this.renderField} type="password" className="form-control"/>
                <Field name="passwordConfirm" label="Confirm Password:" component={this.renderField} type="password" className="form-control"/>
                { this.props.errorMessage
                &&  <div className="alert alert-danger">
                        <strong>Oops!</strong> {this.props.errorMessage}
                    </div> }
                <button action="submit" className="btn btn-primary">Sign up!</button>


let InitializeFromStateForm = reduxForm({
    form: 'initializeFromState'

InitializeFromStateForm = connect(
  state => ({
    profile: state.profile,
    initialValues: state.profile.user
  { fetchRoleList, fetchUserData }

export default InitializeFromStateForm;

I do believe action creator will be useful as well:

export function fetchUserData(user_id) {
    user_id = user_id ? user_id : '';

    const authorization = localStorage.getItem('token');
    const request = axios.get(`${ROOT_URL}/user/${user_id}`, {
      headers: { authorization }

    return {
        type: FETCH_USER,
        payload: request

Source: (StackOverflow)