-
Read some more Full-stack React , TS & Node. Learning about React lifecycle methods in class components
-
When a component is mounting we have access to the follow methods:
constructorthe class contructor used for initalising stategetDerivedStateFromProps, used for basing state on prop from a parent component. Use carefully as can cause re-rendersrenderused to render out JSXcomponentDidMount, happens after a component has initialised . A good place for API calls.UNSAFE_componentWillMount, as the methods implies, legacy method. Avoid!
-
when a component is updating, we have access to the following methods:
shouldComponentUpdate, used to decide if a re-redner should happen or not.getSnapshotBeforeUpdate, capture the state of the dom before a render happens. Usually used alongsidecomponentDidUpdatecomponentDidUpdate, run immediately after a re-render completes. Can make additional changes to the dom here, or after state. Important to have an exit condition so you dont create an infinite loop.
-
when a component is unmounting, we have access to the following methods:
componentWillUnmount, used for cleanup work like removing event listeners or subscriptions
-
Tap into these lifecyles to help control re-renders. If re-renders get out of controls, the UX will suffer.
-
React team recommendations:
componentDidUpdateis useful for triggering behaviour based on a prop change.React.memocan control re-renders only when a prop has changed instead of when the parent changes.- Make your component fully controlled, so it has no state of it’s own. this usually means drilling a prop down many components deeps which can be annoying.
- use
componentDidMountfor rendering state based on an API call. NotecomponentDidMountonly ever runs just once. ComponentDidUpdateis useful for managing state based on prop changes. But generally try to avoid using derived state. Try to just use props directly and have state managed from a parent component.
-