Bird
Raised Fist0
NextJSframework~20 mins

Client-side error boundaries in NextJS - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Client-side Error Boundary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when an error occurs inside a client-side error boundary in Next.js?

Consider a client-side error boundary component in Next.js wrapping a child component that throws an error during rendering. What will the user see?

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

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

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

  return children;
}

function BuggyComponent() {
  throw new Error('Crash!');
}

export default function Page() {
  return (
    <ErrorBoundary>
      <BuggyComponent />
    </ErrorBoundary>
  );
}
AThe page crashes and shows a blank screen with a console error.
BThe error is ignored and the buggy component renders nothing silently.
CThe error boundary catches the error and displays 'Something went wrong.' message.
DNext.js automatically reloads the page to recover from the error.
Attempts:
2 left
💡 Hint

Think about what an error boundary is designed to do in React and Next.js.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly defines a client-side error boundary in Next.js?

Choose the code that correctly implements a client-side error boundary using React hooks in Next.js.

A
function ErrorBoundary({ children }) {
  const [hasError, setHasError] = React.useState(false);
  React.useEffect(() =&gt; {
    const handleError = () =&gt; setHasError(true);
    window.addEventListener('error', handleError);
    return () =&gt; window.removeEventListener('error', handleError);
  }, []);
  if (hasError) {
    return &lt;div&gt;Error occurred&lt;/div&gt;;
  }
  return children;
}
B
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) {
      return &lt;div&gt;Error occurred&lt;/div&gt;;
    }
    return this.props.children;
  }
}
C
function ErrorBoundary({ children }) {
  const [hasError, setHasError] = React.useState(false);
  React.useEffect(() =&gt; {
    try {
      children;
    } catch {
      setHasError(true);
    }
  }, []);
  if (hasError) {
    return &lt;div&gt;Error occurred&lt;/div&gt;;
  }
  return children;
}
D
function ErrorBoundary({ children }) {
  const [error, setError] = React.useState(null);
  if (error) {
    return &lt;div&gt;Error occurred&lt;/div&gt;;
  }
  return children;
}
Attempts:
2 left
💡 Hint

Remember that React error boundaries cannot catch errors inside event handlers or async code, so a window error listener is sometimes used.

🔧 Debug
advanced
2:00remaining
Why does this client-side error boundary fail to catch errors thrown in event handlers?

Review the code below. Why does the error boundary not catch errors thrown inside the button's onClick handler?

NextJS
function ErrorBoundary({ children }) {
  const [hasError, setHasError] = React.useState(false);
  React.useEffect(() => {
    const handleError = () => setHasError(true);
    window.addEventListener('error', handleError);
    return () => window.removeEventListener('error', handleError);
  }, []);
  if (hasError) {
    return <div>Something went wrong.</div>;
  }
  return children;
}

export default function Page() {
  return (
    <ErrorBoundary>
      <button onClick={() => { throw new Error('Click error'); }}>
        Click me
      </button>
    </ErrorBoundary>
  );
}
ABecause errors in event handlers are not caught by React error boundaries or window error events by default.
BBecause the error boundary is missing a try-catch block around the button's onClick handler.
CBecause the window error event listener is not properly removed in the cleanup function.
DBecause the button component is outside the error boundary's children.
Attempts:
2 left
💡 Hint

Think about how React handles errors in event handlers differently from render errors.

state_output
advanced
2:00remaining
What is the value of hasError state after an error is caught by this client-side error boundary?

Given the code below, what will be the value of hasError after an error event is triggered?

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

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

  return hasError ? <div>Error occurred</div> : children;
}

// Somewhere else in the app, an error is thrown causing a window error event.
Aundefined
Bfalse
Cnull
Dtrue
Attempts:
2 left
💡 Hint

Consider what the event listener does when an error occurs.

🧠 Conceptual
expert
2:00remaining
Why are client-side error boundaries important in Next.js applications?

Choose the best explanation for why client-side error boundaries are used in Next.js apps.

AThey automatically fix bugs in the code by retrying failed components without user intervention.
BThey prevent the entire React component tree from unmounting when a child component throws an error during rendering, improving user experience by showing fallback UI instead of a blank page.
CThey enable server-side rendering to catch errors before sending HTML to the client.
DThey replace the need for try-catch blocks in all asynchronous code throughout the app.
Attempts:
2 left
💡 Hint

Think about what happens when a React component crashes and how error boundaries help.

Practice

(1/5)
1. What is the main purpose of client-side error boundaries in Next.js?
easy
A. To catch errors in UI components and show a fallback UI instead of crashing the whole app
B. To improve server-side rendering speed
C. To handle database connection errors
D. To optimize image loading performance

Solution

  1. Step 1: Understand error boundaries role

    Error boundaries catch errors in parts of the UI to prevent the entire app from crashing.
  2. Step 2: Identify their main effect

    They show a fallback UI so users see a friendly message instead of a broken screen.
  3. Final Answer:

    To catch errors in UI components and show a fallback UI instead of crashing the whole app -> Option A
  4. Quick Check:

    Error boundaries catch UI errors = C [OK]
Hint: Error boundaries catch UI errors and show fallback UI [OK]
Common Mistakes:
  • Confusing error boundaries with server-side features
  • Thinking they handle backend or database errors
  • Assuming they improve performance directly
2. Which of the following is the correct way to define a client-side error boundary component in Next.js using React hooks?
easy
A. function ErrorBoundary({ children }) { try { return children; } catch { return ; } }
B. class ErrorBoundary extends React.Component { render() { return this.props.children; } }
C. function ErrorBoundary() { return
Error
; }
D. const ErrorBoundary = () => { return children; }

Solution

  1. Step 1: Identify hook-based error boundary pattern

    Client-side error boundaries in Next.js use try/catch inside functional components to catch errors during rendering.
  2. Step 2: Check each option

    function ErrorBoundary({ children }) { try { return children; } catch { return ; } } uses try/catch inside a function component returning children or fallback UI, which is correct.
  3. Final Answer:

    function ErrorBoundary({ children }) { try { return children; } catch { return <Fallback />; } } -> Option A
  4. Quick Check:

    Try/catch in function component = A [OK]
Hint: Use try/catch inside functional component for client error boundaries [OK]
Common Mistakes:
  • Using class components instead of functional components
  • Not using try/catch to catch errors
  • Returning children without error handling
3. Given this client-side error boundary component in Next.js:
function ErrorBoundary({ children }) {
  try {
    return children;
  } catch {
    return <div>Error occurred</div>;
  }
}

function BuggyComponent() {
  throw new Error('Bug!');
}

export default function App() {
  return (
    <ErrorBoundary>
      <BuggyComponent />
    </ErrorBoundary>
  );
}

What will be rendered on the page?
medium
A. output
B.
Error occurred
C. Nothing is rendered
D. The app crashes with an uncaught error

Solution

  1. Step 1: Understand error throwing in BuggyComponent

    BuggyComponent throws an error immediately when rendered.
  2. Step 2: Check ErrorBoundary behavior

    ErrorBoundary tries to render children inside try block; error triggers catch block returning fallback UI <div>Error occurred</div>.
  3. Final Answer:

    <div>Error occurred</div> -> Option B
  4. Quick Check:

    Error caught, fallback shown = D [OK]
Hint: Error in child triggers catch, fallback UI renders [OK]
Common Mistakes:
  • Expecting the app to crash instead of showing fallback
  • Thinking children render despite error
  • Confusing output with component name
4. Identify the problem in this client-side error boundary code snippet:
function ErrorBoundary({ children }) {
  try {
    return children;
  } catch (error) {
    console.log(error);
  }
}

export default function App() {
  return (
    <ErrorBoundary>
      <div>Hello</div>
    </ErrorBoundary>
  );
}

What issue will occur when an error happens inside children?
medium
A. The error is caught and fallback UI is shown
B. The error is logged and children still render
C. The app crashes due to syntax error
D. No fallback UI is returned, so the component renders nothing

Solution

  1. Step 1: Analyze catch block behavior

    The catch block logs the error but does not return any UI.
  2. Step 2: Understand React rendering rules

    Without a return in catch, the component returns undefined, rendering nothing on error.
  3. Final Answer:

    No fallback UI is returned, so the component renders nothing -> Option D
  4. Quick Check:

    Missing return in catch = renders nothing [OK]
Hint: Always return fallback UI in catch block [OK]
Common Mistakes:
  • Forgetting to return fallback UI in catch
  • Assuming logging error is enough
  • Expecting children to render after error
5. You want to create a client-side error boundary in Next.js that catches errors in nested components and logs the error before showing fallback UI. Which approach correctly combines error catching, logging, and fallback rendering?
hard
A. function ErrorBoundary({ children }) { try { return children; } catch (error) { return
Something went wrong.
; } }
B. function ErrorBoundary({ children }) { try { return children; } catch { return
Something went wrong.
; } }
C. function ErrorBoundary({ children }) { try { return children; } catch (error) { console.error(error); return
Something went wrong.
; } }
D. function ErrorBoundary({ children }) { try { return children; } catch (error) { console.log('Error caught'); } }

Solution

  1. Step 1: Check error catching and logging

    function ErrorBoundary({ children }) { try { return children; } catch (error) { console.error(error); return
    Something went wrong.; } } catches error, logs it with console.error, then returns fallback UI.
  2. Step 2: Verify fallback UI return

    function ErrorBoundary({ children }) { try { return children; } catch (error) { console.error(error); return
    Something went wrong.
    ; } } returns fallback UI after logging, ensuring user sees message and error is logged.
  3. Final Answer:

    function ErrorBoundary({ children }) { try { return children; } catch (error) { console.error(error); return <div>Something went wrong.</div>; } } -> Option C
  4. Quick Check:

    Error caught, logged, fallback returned = A [OK]
Hint: Catch error, log it, then return fallback UI [OK]
Common Mistakes:
  • Not logging the error before fallback
  • Not returning fallback UI after catching error
  • Logging without returning fallback UI