React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 5

Explain the lifecycle methods of a React component.

Answer:

React components, especially class components, have lifecycle methods that allow developers to hook into specific points in the component's lifecycle. These methods provide control over the behavior of components during their creation, updating, and removal from the DOM. Here are the primary lifecycle methods of a React component:

1. Mounting

Mounting is the phase when a component is being inserted into the DOM.

  • constructor(props):

    • Called before the component is mounted.
    • Used for initializing state and binding event handlers.
    • Avoid side effects here.
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = { count: 0 };
      }
    }
  • static getDerivedStateFromProps(props, state):

    • Invoked right before rendering, both on the initial mount and subsequent updates.
    • Used to update the state based on props.
    • Rarely used and should be static, meaning it has no access to this.
    static getDerivedStateFromProps(nextProps, prevState) {
      if (nextProps.someValue !== prevState.someValue) {
        return { someValue: nextProps.someValue };
      }
      return null;
    }
  • render():

    • Required method.
    • Returns the JSX representing the component's UI.
    • Pure function, should not modify component state.
    render() {
      return <div>{this.state.count}</div>;
    }
  • componentDidMount():

    • Called after the component is mounted.
    • Ideal for making network requests, setting up subscriptions, and other side effects.
    componentDidMount() {
      // Fetch data or set up a timer
    }

2. Updating

Updating is the phase when a component is being re-rendered as a result of changes to either its props or state.

  • static getDerivedStateFromProps(props, state):

    • Same as in the mounting phase.
  • shouldComponentUpdate(nextProps, nextState):

    • Called before rendering when new props or state are received.
    • Return true to proceed with rendering or false to skip rendering.
    • Used for performance optimization.
    shouldComponentUpdate(nextProps, nextState) {
      return nextProps.someValue !== this.props.someValue;
    }
  • render():

    • Same as in the mounting phase.
  • getSnapshotBeforeUpdate(prevProps, prevState):

    • Called right before the most recently rendered output is committed to the DOM.
    • Captures some information (e.g., scroll position) from the DOM before it changes.
    • Return value is passed to componentDidUpdate.
    getSnapshotBeforeUpdate(prevProps, prevState) {
      if (prevProps.someValue !== this.props.someValue) {
        return { someData: 'some value' };
      }
      return null;
    }
  • componentDidUpdate(prevProps, prevState, snapshot):

    • Called after the component has been updated.
    • Good for handling side effects that are based on previous state or props.
    componentDidUpdate(prevProps, prevState, snapshot) {
      if (prevProps.someValue !== this.props.someValue) {
        // Perform operations based on new props
      }
    }

3. Unmounting

Unmounting is the phase when a component is being removed from the DOM.

  • componentWillUnmount():

    • Called right before the component is unmounted and destroyed.
    • Used for cleanup, such as invalidating timers, canceling network requests, or cleaning up subscriptions.
    componentWillUnmount() {
      // Clean up code
    }

4. Error Handling

React components also have lifecycle methods for handling errors during rendering, in lifecycle methods, and in constructors of the whole tree.

  • static getDerivedStateFromError(error):

    • Called when an error is thrown in a descendant component.
    • Used to update the state so the next render shows a fallback UI.
    static getDerivedStateFromError(error) {
      return { hasError: true };
    }
  • componentDidCatch(error, info):

    • Called after an error has been thrown in a descendant component.
    • Used to log error information or perform side effects.
    componentDidCatch(error, info) {
      // Log error to an error reporting service
    }

Functional Components with Hooks

Functional components use hooks to handle lifecycle events. For example:

  • useEffect:

    • Combines componentDidMount, componentDidUpdate, and componentWillUnmount.
    • The effect is executed after render and can return a cleanup function.
    useEffect(() => {
      // Perform side effect
      return () => {
        // Cleanup
      };
    }, [dependencies]);

Understanding and utilizing these lifecycle methods effectively allows developers to manage component behavior and side effects in a predictable and organized manner.

Recent job openings