In which of the react lifecylcle methods (https://facebook.github.io/react/docs/react-component.html) is it allowed/forbidden/recommended/not recommended to dispatch redux actions? Why?
Say my stateless component uses data loaded from the server, is it ok to dispatch an action during render()
to schedule an ajax call?
You can dispatch an action by directly using store. dispatch(). However, it is more likely that you access it with react-Redux helper method called connect(). You can also use bindActionCreators() method to bind many action creators with dispatch function.
The app code dispatches an action to the Redux store, like dispatch({type: 'counter/incremented'}) The store runs the reducer function again with the previous state and the current action , and saves the return value as the new state.
In React v16. 3, componentWillMount() , componentWillReceiveProps() , and componentWillUpdate() are marked as unsafe legacy lifecycle methods for deprecation process. They have often been misused and may cause more problems with the upcoming async rendering.
Answer is opinionated, but it's frowned upon in general: lifecycle methods get called in reaction to a state change up the component tree, but dispatching an action will probably initiate another state change. It's the event-handler cascading update situation that redux tries to avoid: you should make state changes in response to actions and nothing else or else you'll have these reactive loops. The state change happens all at once.
In practice this rule gets relaxed for convenience sake pretty often. So there's no real right answer! Like most things in software dev it's nuanced.
Other answer is right about not doing that (or anything impure) in render though: the event you want is probably "when this component is being mounted" vs "whenever its render gets called" which is better handled by constructor
or componentWillMount
. Also, anything you'd want to have done in render is better served by componentDidMount
/componentWillUpdate
/componentDidUpdate
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With