DEV Community

Cover image for React Quiz #02 — Class Components vs Functional Components in React
Quizzesforyou
Quizzesforyou

Posted on • Edited on • Originally published at Medium

React Quiz #02 — Class Components vs Functional Components in React

Check out the interactive React Class vs Functional component quiz *https://quizzesforyou.com/quiz/react*classvsfunctional

React, a popular JavaScript library for building user interfaces provides developers with two fundamental approaches for creating reusable and modular components class components and functional components. Let's explore them in this article,

Class Components:

  • Class components were the primary way of creating components in React before the introduction of React Hooks in version 16.8.

  • They encapsulate the component’s logic, state, and lifecycle methods.

  • Class components are suitable for complex and stateful components.

State and Lifecycle:

  • Class components can manage the state using the internal state object.

  • State updates trigger the re-rendering of the component.

  • Lifecycle methods (e.g., componentDidMount(), componentDidUpdate(), componentWillUnmount()) allow performing actions at specific stages of a component’s lifecycle.

Example of a Class Component:

class Counter extends React.Component {
    constructor(props) {
         super(props);
         this.state = {
             count: 0
         };
     }

    componentDidMount() {
         console.log('Component mounted');
     }
    componentDidUpdate() {
         console.log('Component updated');
     }
    componentWillUnmount() {
         console.log('Component will unmount');
     }
    // … Remaining code …
}
Enter fullscreen mode Exit fullscreen mode

Functional Components:

  • Functional components are defined as plain JavaScript functions that return JSX elements.

  • They are suitable for simpler components that don’t require state management or lifecycle methods.

  • Functional components are easier to understand, test, and maintain.

No State or Lifecycle:

  • Functional components do not have an internal state or lifecycle methods.

  • They receive data as props and render JSX based on that data.

Example of a Functional Component:

import React from 'react'; 
const Greeting = ({ name }) => 
     return <h1>Hello, {name}!</h1>;
};
Enter fullscreen mode Exit fullscreen mode

React Hooks:

  • Hooks were added to React in version 16.8

  • React hooks, such as useState and useEffect, allow functional components to manage state and perform side effects.

  • Hooks enhance functional components and make them more versatile for managing state and lifecycle behavior.

Lifecycle Methods and Equivalent Hooks:

  • React hooks provide equivalents to the lifecycle methods found in class components.

The table above shows the class component lifecycle methods on the left column and their equivalent React Hooks on the right column.

Since version 16.8, React Recommends Functional components as they offer several benefits over class components.

In summary, Functional components in React enhances code readability, simplify testing, improve performance, and facilitate easier debugging.


Check out the interactive React Class vs Functional component quiz https://quizzesforyou.com/quiz/reactclassvsfunctional

1. Which component type is recommended for leveraging React’s error boundary concept?

a) Functional component

b) Class component

c) Both types can be used with error boundaries

Answer: b) Class component

Still[current version 18.2] Class components are recommended for utilizing React’s error boundary concept. Error boundaries are created by extending the React.Component class and implementing the componentDidCatch and static getDerivedStateFromError lifecycle methods, which are only available in class components. Error Boundaries can be also implemented in the Functional component.

2. Which hook can be used to replicate the behavior of "componentDidUpdate" with specific state or prop values to watch for changes?

a) useEffect(() => {...}, [])

b) useEffect(() => {...}, [state/prop])

c) useEffect(() => { return () => {...} }, [])

Answer: b) useEffect(() => {...}, [state/prop])

The useEffect hook with a dependency array containing the state or prop values to watch for changes replicates the behavior of componentDidUpdate and is triggered when those values change.

3. Which component type allows better optimization for code-splitting and lazy loading?

a) Functional components

b) Class components

c) Both component types offer the same level of optimization for code-splitting

Answer: a) Functional components

Functional components, especially when used with React’s lazy loading and Suspense features, provide better optimization for code-splitting. They enable more granular control over loading components on-demand, improving performance and reducing bundle size.

4. Which lifecycle method is used to perform state updates after a class component has been re-rendered?

a) componentDidUpdate

b) shouldComponentUpdate

c) componentWillReceiveProps

Answer: a) componentDidUpdate

The componentDidUpdate lifecycle method is invoked after a component has been re-rendered, allowing for state updates or additional side effects based on the new props or state values.

5. Which hook provides similar functionality to componentWillUnmount in class components?

a) useEffect(() => { return () => {...} }, [])

b) useMemo

c) React.memo

Answer: a) useEffect(() => { return () => {...} }, [])

The useEffect hook with a cleanup function returned replicates the behavior of componentWillUnmount and is triggered when the component is unmounted.

6. React Class components are simpler to test and lead to better performance when compared to Functional components.

a) True

b) False

Ans: False

7. What is the equivalent hook for the shouldComponentUpdate lifecycle method in class components?

a) useState

b) useMemo

c) useEffect

Answer: b ) useMemo

8. Which lifecycle method should be used in a class component to prevent unnecessary re-renders?

a) shouldComponentUpdate

b) componentDidUpdate

c) componentWillReceiveProps

Answer: a) shouldComponentUpdate

The shouldComponentUpdate lifecycle method allows developers to control whether a component should re-render or not, preventing unnecessary re-renders and optimizing performance.

9. What is the equivalent hook for getSnapshotBeforeUpdate in class components?

a) useEffect(() => {...}, [])

b) useMemo

c) There is no direct hook equivalent

Answer: c) There is no direct hook equivalent

While React Hooks provide alternatives for most lifecycle methods, there is currently no direct hook equivalent for getSnapshotBeforeUpdate. However, its functionality can be achieved using refs or other approaches specific to the use case.

10. Which hook can be used to achieve the behavior of getDerivedStateFromProps in class components?

a) useMemo

b) useEffect

c) Both useMemo and useEffect

Answer: c) Both useMemo and useEffect

Both useMemo and useEffect can be used to achieve the behavior of getDerivedStateFromProps, depending on the specific use case and requirements of the component.


Visit https://quizzesforyou.com for more such quizzes

Top comments (0)