Bird
Raised Fist0
NextJSframework~10 mins

Why error boundaries matter in NextJS - Test Your Understanding

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create an error boundary component in Next.js.

NextJS
import React from 'react';

function ErrorBoundary({ children }) {
  const [hasError, setHasError] = React.useState(false);

  React.useEffect(() => {
    const handleError = () => setHasError(true);
    window.addEventListener('error', handleError);
    return () => window.removeEventListener('error', [1]);
  }, []);

  if (hasError) {
    return <div>Something went wrong.</div>;
  }

  return children;
}
Drag options to blanks, or click blank then click option'
AsetHasError
BhandleError
Cchildren
DhasError
Attempts:
3 left
💡 Hint
Common Mistakes
Removing a different function than the one added causes the listener to stay active.
Trying to remove the listener with a variable that is not a function.
2fill in blank
medium

Complete the code to catch errors in a React component using Next.js error boundaries.

NextJS
import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static [1](error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <h1>Oops! Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
Drag options to blanks, or click blank then click option'
AgetDerivedStateFromError
BcomponentDidCatch
CcomponentWillUnmount
DshouldComponentUpdate
Attempts:
3 left
💡 Hint
Common Mistakes
Using lifecycle methods that are not static to update state.
Confusing error boundary methods with normal component lifecycle methods.
3fill in blank
hard

Fix the error in the Next.js error boundary component to properly log errors.

NextJS
class ErrorBoundary extends React.Component {
  componentDidCatch(error, info) {
    console.log([1]);
  }
  render() {
    return this.props.children;
  }
}
Drag options to blanks, or click blank then click option'
Ainfo
Berror
Cerror, info
Dthis.error
Attempts:
3 left
💡 Hint
Common Mistakes
Logging only one argument misses important error details.
Trying to access error as a property of this.
4fill in blank
hard

Fill both blanks to create a functional error boundary using React hooks in Next.js.

NextJS
import React from 'react';

function ErrorBoundary({ children }) {
  const [hasError, setHasError] = React.useState(false);

  React.useEffect(() => {
    const handleError = () => setHasError(true);
    window.addEventListener('error', [1]);
    return () => window.removeEventListener('error', [2]);
  }, []);

  if (hasError) {
    return <div>Oops! An error occurred.</div>;
  }

  return children;
}
Drag options to blanks, or click blank then click option'
AhandleError
BsetHasError
ChasError
Dchildren
Attempts:
3 left
💡 Hint
Common Mistakes
Using different functions for adding and removing listeners causes memory leaks.
Passing state variables instead of functions to event listeners.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that filters errors by severity in Next.js error logging.

NextJS
const errorSummary = {
  [1]: [2] for (const [key, value] of Object.entries(errors))
  if (value.severity [3] 3)
};
Drag options to blanks, or click blank then click option'
Akey
Bvalue
C>=
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong comparison operator in the filter condition.
Swapping key and value in the comprehension.

Practice

(1/5)
1. What is the main purpose of error boundaries in a Next.js application?
easy
A. To catch JavaScript errors in components and display a fallback UI
B. To improve SEO by optimizing page metadata
C. To handle server-side rendering errors automatically
D. To manage user authentication and sessions

Solution

  1. Step 1: Understand error boundaries role

    Error boundaries catch errors in React components during rendering, lifecycle methods, and constructors.
  2. Step 2: Identify their main benefit

    They prevent the whole app from crashing by showing a fallback UI instead of a broken screen.
  3. Final Answer:

    To catch JavaScript errors in components and display a fallback UI -> Option A
  4. Quick Check:

    Error boundaries catch errors = B [OK]
Hint: Error boundaries catch errors and show fallback UI [OK]
Common Mistakes:
  • Confusing error boundaries with authentication
  • Thinking error boundaries improve SEO
  • Assuming error boundaries handle server errors automatically
2. Which of the following is the correct way to define an error boundary component in Next.js using React functional components?
easy
A. class ErrorBoundary extends React.Component { constructor() { super(); this.state = { hasError: false }; } componentDidCatch() { this.setState({ hasError: true }); } render() { if (this.state.hasError) return
Error occurred
; return this.props.children; } }
B. function ErrorBoundary({ children }) { const [hasError, setHasError] = React.useState(false); if (hasError) return
Error
; return children; }
C. function ErrorBoundary({ children }) { try { return children; } catch { return
Error
; } }
D. class ErrorBoundary extends React.Component { state = { error: null }; render() { if (this.state.error) return
Error
; return this.props.children; } }

Solution

  1. Step 1: Recall error boundary implementation

    Error boundaries must be class components with lifecycle methods like componentDidCatch to catch errors.
  2. Step 2: Check options for correct syntax

    class ErrorBoundary extends React.Component { constructor() { super(); this.state = { hasError: false }; } componentDidCatch() { this.setState({ hasError: true }); } render() { if (this.state.hasError) return <div>Error occurred</div>; return this.props.children; } } correctly defines a class component with constructor, state, componentDidCatch, and render method.
  3. Final Answer:

    class ErrorBoundary extends React.Component { constructor() { super(); this.state = { hasError: false }; } componentDidCatch() { this.setState({ hasError: true }); } render() { if (this.state.hasError) return <div>Error occurred</div>; return this.props.children; } } -> Option A
  4. Quick Check:

    Error boundaries require class + componentDidCatch = C [OK]
Hint: Error boundaries must be class components with componentDidCatch [OK]
Common Mistakes:
  • Trying to create error boundaries as functional components
  • Missing componentDidCatch lifecycle method
  • Not initializing state to track errors
3. Given the following error boundary component and a child component that throws an error, what will be rendered?
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  componentDidCatch(error, info) {
    this.setState({ hasError: true });
  }
  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

function BuggyComponent() {
  throw new Error('Bug!');
  return <div>No bugs</div>;
}

// Usage
<ErrorBoundary>
  <BuggyComponent />
</ErrorBoundary>
medium
A. Uncaught Error: Bug!
B. No bugs
C.

Something went wrong.

D. Blank screen

Solution

  1. Step 1: Understand error throwing in child

    BuggyComponent throws an error immediately when rendered.
  2. Step 2: Check error boundary response

    ErrorBoundary catches the error in componentDidCatch and sets hasError to true, rendering fallback UI.
  3. Final Answer:

    <h1>Something went wrong.</h1> -> Option C
  4. Quick Check:

    Error caught, fallback UI shown = A [OK]
Hint: ErrorBoundary shows fallback UI when child throws error [OK]
Common Mistakes:
  • Expecting child component output despite error
  • Thinking error is uncaught and crashes app
  • Assuming blank screen instead of fallback UI
4. You have this error boundary component but it does not catch errors as expected. What is the likely problem?
function ErrorBoundary({ children }) {
  try {
    return children;
  } catch (error) {
    return <div>Error occurred</div>;
  }
}
medium
A. Try-catch works fine for error boundaries in functional components
B. Error boundaries must be class components with componentDidCatch method
C. You forgot to wrap children in a React.Fragment
D. You need to use useErrorBoundary hook instead

Solution

  1. Step 1: Analyze error boundary implementation

    Try-catch inside a functional component does not catch errors during rendering lifecycle in React.
  2. Step 2: Recall React error boundary requirements

    Error boundaries must be class components implementing componentDidCatch lifecycle method to catch errors properly.
  3. Final Answer:

    Error boundaries must be class components with componentDidCatch method -> Option B
  4. Quick Check:

    Functional try-catch won't catch render errors = A [OK]
Hint: Error boundaries require class + componentDidCatch, not try-catch [OK]
Common Mistakes:
  • Using try-catch in functional components expecting error boundary behavior
  • Assuming React has a useErrorBoundary hook
  • Thinking wrapping children in fragments fixes error catching
5. You want to add a reset button in your error boundary to let users try again after an error. Which approach correctly implements this behavior?
hard
A. Use a useEffect hook to reset error state automatically after 5 seconds
B. Reload the entire page using window.location.reload() when the button is clicked
C. Wrap the reset button in a try-catch block to prevent errors
D. Add a button that calls this.setState({ hasError: false }) inside the error boundary's fallback UI

Solution

  1. Step 1: Understand reset behavior in error boundaries

    Resetting error state allows the component tree to re-render normally after an error.
  2. Step 2: Identify correct reset method

    Calling this.setState({ hasError: false }) inside the error boundary resets the error state and shows children again.
  3. Final Answer:

    Add a button that calls this.setState({ hasError: false }) inside the error boundary's fallback UI -> Option D
  4. Quick Check:

    Reset error state with setState = D [OK]
Hint: Reset error by setting hasError false in state [OK]
Common Mistakes:
  • Reloading page instead of resetting state
  • Using try-catch around reset button unnecessarily
  • Relying on automatic reset with useEffect without user action