-
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:
constructor
the class contructor used for initalising stategetDerivedStateFromProps
, used for basing state on prop from a parent component. Use carefully as can cause re-rendersrender
used 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 alongsidecomponentDidUpdate
componentDidUpdate
, 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:
componentDidUpdate
is useful for triggering behaviour based on a prop change.React.memo
can 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
componentDidMount
for rendering state based on an API call. NotecomponentDidMount
only ever runs just once. ComponentDidUpdate
is 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.
-