I've been using the React - Redux - Typescript stack for a while and I'm loving it so far. However, since I'm quite new to Redux, I've been wondering about this certain topic. Is dispatching Redux actions (and thunks) considered expensive operations and should be used sparingly, or should it be used as much as setState is used?
Let's say the Redux state has a single reducer that manages user information:
const initialState = {
firstName: '',
lastName: ''
}
And to change these fields, let say we have actions like setFirstName
, setLastName
, etc... just for simplicity's sake.
And let's say in the View I have an input element in render()
:
<input onChange={this.firstNameInputChangeListener} placeholder="First Name"/>
Considering setFirstName
has been mapped to the component:
export default connect(state => state, { setFirstName })(ThisComponent);
Is it optimal to dispatch an action every time there's a change in the input:
public firstNameInputChangeListener = (event) => {
this.props.setFirstName(event.target.value);
}
Or is it better to create local component state, bind the state to the Change Listener and only dispatch an action when the form is submitted:
public state = {
firstName: this.props.firstName;
}
public firstNameInputChangeListener = (event) => {
this.setState({ firstName: event.target.value });
}
public submitButtonListener = (event) => {
this.props.setFirstName(this.state.firstName);
}
What do you guys think?
The cost of actually dispatching an action is:
combineReducers()
Generally, the middleware and the reducer logic are not the bottlenecks - it's updating the UI that can be expensive. With React-Redux, each connected component instance is a separate subscriber. If you have a connected List with 10000 connected ListItems, that's 10001 subscribers.
The Redux FAQ has entries discussing app performance and scalability, and ways to cut down on subscriber notifications.
For a form specifically, it's unlikely that the rest of the app needs to be updated on every keystroke in the form. For that, it's very reasonable to debounce the dispatch. My blog post Practical Redux, Part 7: Form Change Handling and Data Editing shows a reusable component that can wrap inputs or forms to enable fast updates in the UI, while also debouncing the dispatch of a Redux action.