Lifecycle

  • Do we have lifecycle methods in functional components — No!!

Class components

Mounting

  • constructor(): Called when the component is initiated. It’s used for initializing state and binding methods.
  • static getDerivedStateFromProps(): Invoked right before calling the render method. It allows the state to be updated based on props.
  • render(): The only required method in a class component. It returns the JSX that makes up the component’s UI.
  • componentDidMount(): Called after the component is rendered. It’s used for initializing data, making API calls, or setting up subscriptions.

Updating

  • static getDerivedStateFromProps(): Also called during updating.
  • shouldComponentUpdate(): Determines if the component should re-render or not. Used for performance optimization.
  • render(): Re-rendered with new props or state.
  • getSnapshotBeforeUpdate(): Captures some information (e.g., scroll position) before the DOM is potentially changed.
  • componentDidUpdate(): Called after the component is re-rendered. It’s used for performing DOM operations or network requests based on previous state/props.

Unmounting

  • componentWillUnmount(): Called right before the component is removed from the DOM. Used for cleanup tasks such as invalidating timers or cancelling network requests.

Error Handling

  • static getDerivedStateFromError(): Used to update state in case of an error during rendering.
  • componentDidCatch(): Used to log error information.

Hooks relationship

  • componentDidMount: Use useEffect with an empty dependency array []
  • componentDidUpdate: Use useEffect with the specific dependencies that should trigger the effect
  • componentWillUnmount: Use the cleanup function inside useEffect