Skip to content

Latest commit

History

History
26 lines (23 loc) 路 2.08 KB

2021-02-13.md

File metadata and controls

26 lines (23 loc) 路 2.08 KB
publish_date
2021-02-13
  • 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 state
      • getDerivedStateFromProps , used for basing state on prop from a parent component. Use carefully as can cause re-renders
      • render used to render out JSX
      • componentDidMount, 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 alongside componentDidUpdate
      • 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. Note componentDidMount only 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.