Component initialization
This simulator allows you to step through each lifecycle method as a component is initialized and mounted, and watch how this.state and this.props respond to various actions at each point in time.
How to use:
- Press Instantiate to start the simulation.
- Press Set this.state to run
this.state = { next: 1 }. - Press Call setState to simulate a call to
this.setStatethat incrementsthis.state.next. - Press Change props to simulate a change to the component’s input props, e.g. from a call to a Redux store’s
dispatchfunction. - Press Reset to start over.
- Set initial state via
this.state = { ... }. - Bind callbacks.
- Do not subscribe to events, dispatch redux actions, or otherwise cause side effects.
- Similar to the
constructor, but can cause side effects. - When possible, use
constructororcomponentDidMountinstead. - Main use case is subscribing to events and dispatching actions in non-browser environments.
this.staterender
- Do not call
this.setState(). - Do not cause side effects.
- Just create an element and return it.
- Subscribe to events.
- Dispatch actions.
- Make any necessary calls to the DOM.
- Not called in non-browser evironments, as there is no DOM to mount into.
Lifecycle Simulator
Not IntantiatedProps
undefinedState
undefinedNotes
State doesn’t change immediately
When you call this.setState(), React will not immediately update this.state. Instead, an update will be queued for some point in the future. This extra step appears as Update this.state in the simulator.
Note that in the constructor, you can directly assign to this.state, and so any changes will happen immediately.
Why avoid componentWillMount?
The componentWillMount method can accomplish many of the same tasks as constructor and componentDidMount. You can call this.setState() to change state, and can also cause side effects that change
the input props. So why avoid componentWillMount?
If you cause a change in props in componentDidMount, it is obvious that the component will need to re-render. However, if you cause a change in props within componentWillMount, React’s behavior is far from obvious.
When a component’s props change within componentWillMount, the following call to render will still use the old props.
The componentWillMount method can accomplish many of the same tasks as constructor and componentDidMount. However, unless you’re using server-side rendering, it cannot accomplish any more than other lifecycle methods. Avoiding it makes it easier to reason about your components.
Props and state updates
Want to know what happens after your component is mounted? The prop and state change simulators will be released shortly – and React Armory members will get early access! Join now for free to make sure you don’t miss out:
React Armory is growing. Join in to be the first to experience new lessons, examples and resources.