Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/redux: In which lifecycle methods is it allowed/forbidden/frowned upon/encouraged to dispatch actions? Why?

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?

like image 321
jhegedus Avatar asked Jun 26 '17 16:06

jhegedus


People also ask

Which of the following functions can be used to dispatch actions in Redux?

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.

What happens when you dispatch an action Redux?

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.

What is unsafe lifecycle in React?

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.


1 Answers

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.

like image 115
Alex Guerra Avatar answered Oct 14 '22 05:10

Alex Guerra