Search code examples
reactjsreduxreact-redux-form

OK to update state in react components directly when using react-redux?


I see examples on the web where people have things like click events that they handle with function calls in the components themselves then change state directly by doing basic things like:

saveCourse(event) {
  this.setState({saving: true});
}

I had thought that when using react-redux it is important to make all state changes in reducers based on action calls.

Please tell me if I somehow missed the common usage pattern of react-redux.


Solution

  • It's perfectly fine to continue using React's own State mechanism in tandem with Redux store.

    Here's how I make sense of the two choices: If a piece of data (and changes happening to it) are local to a single component and its immediate child components, use State. Update it the way you normally would with React.

    If a piece of data is to be used across your application, in various components that may or may not reside in the same component tree, or may be separated from each other by various intermediate components, then use Redux, so you don't end up passing props and handler callbacks up and down the chain.

    Here's an example to illustrate the point: Imagine you have a Contacts list in your Redux store. And an addContact reducer to add a new contact to this list. Items on this list may be displayed in various shapes and places across your application. For example, a menu item on the side bar may show the count of items are on the list, while another div in the main panel may list the items and their details. All good so far.

    Now, you need to create a NewContact component that renders a form and the necessary input fields to let the user add a new contact to the list. The inputs on this form can be Controlled Components, updating the internal state of the NewContact component, completely bypassing the Redux store. Upon form submission, your component will dispatch an addNewContact action with the proper payload, at which point the new contact will be added to the list via the Redux mechanism, propagating the necessary updates to the rest of your application.

    This is a valid example for the hybrid use of Redux Store and React State simultaneously.

    Now, could you manage the state of your NewContact form in Redux as well? Absolutely! But should you? Your call. You don't have to, unless there's some benefit in doing that.