Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Fundamentals
  1. 1.Introduction to React & Development Environment
  2. 2.JSX, Components & Props
  3. 3.Managing Component State with useState
  4. 4.Event Handling & Conditional Rendering
  5. 5.Rendering Lists & Basic useEffect
  6. 6.Deep Dive into useEffect Hook
  7. 7.useRef and useReducer for Complex State
  8. 8.Optimizing Performance with useMemo & useCallback
  9. 9.Context API & Custom Hooks for Reusability
  10. 10.Client-Side Routing with React Router
  11. 11.Forms, Validation & Data Fetching Patterns
  12. 12.Advanced Performance Optimization & Reconciliation
  13. 13.State Management Libraries (Redux Toolkit & Alternatives)
  14. 14.Testing React Components with Jest & React Testing Library
  15. 15.Advanced React Features & Modern Concepts
React Fundamentals
04

React · Lesson 4 of 15 · 3 min

Event Handling & Conditional Rendering

This is how you explain the flow from user action to UI update and justify your choice of rendering pattern in an interview.

After this, you'll be able to build components that respond to user input and change what's on the screen. This isn't just about making a button work; it's about controlling the entire render lifecycle based on state.

Connecting User Actions to State Changes

An event handler is a function you pass to a JSX prop like onClick or onChange. When a user interacts with the element, React calls your function. The primary job of that function is usually to update state.

The most common mistake is calling the function instead of passing it.

  • onClick={handleClick}: Correct. You are passing a reference to the handleClick function. React will call it later, when the click happens.
  • onClick={handleClick()}: Wrong. This calls handleClick during the render. The return value of the function (often undefined) is passed to onClick, so nothing happens when the user clicks.

If you need to pass arguments to your handler, use an inline arrow function: onClick={() => deleteItem(item.id)}. This creates a new function that, when called by React, will execute your handler with the correct argument.

In an interview, you might be asked about React's SyntheticEvent. It's a cross-browser wrapper around the browser's native event. It gives you a consistent API (e.g., e.preventDefault() works the same everywhere). You don't need to know the implementation details, just that it's an abstraction layer for compatibility and reliability.

This entire flow—from user action to UI update—is the core loop of a React application.

The Complete Pattern: Toggling UI

Event handling and conditional rendering are two sides of the same coin. An event updates the state, and conditional rendering reads that state to decide what the UI should look like.

Here is the complete pattern in a component that toggles a message's visibility.

import React, { useState } from 'react';

function ToggleMessage() {
  const [isVisible, setIsVisible] = useState(true);

  const handleToggle = () => {
    setIsVisible(currentVisibility => !currentVisibility);
  };

  return (
    <div>
      <button onClick={handleToggle}>
        {isVisible ? 'Hide Message' : 'Show Message'}
      </button>

      {isVisible && <p>This is the secret message.</p>}
    </div>
  );
}

This short example demonstrates everything:

  1. State: isVisible holds the single piece of information that controls the UI.
  2. Event Handler: handleToggle updates that state. We use the function form of the state setter (setIsVisible(current => !current)) to ensure we're always working with the latest state value.
  3. Conditional Rendering: The button's text uses a ternary operator, and the paragraph's visibility uses the logical && operator. Both are driven by the isVisible state.

Choosing the Right Conditional Rendering Pattern

You have three main tools for conditional rendering. Choosing the right one signals that you value code clarity.

1. Ternary Operator (? :) Use this for a simple, inline if/else choice. It's best when you need to render one thing or another.

{isLoading ? <Spinner /> : <Dashboard />}

2. Logical AND (&&) Use this when you want to render something or nothing. It works because in JavaScript, true && expression evaluates to expression, and false && expression evaluates to false. React renders nothing for false.

{error && <ErrorMessage message={error.message} />}

The trap: Be careful with falsy values. If count is 0, the expression count && <Component /> will render the number 0 to the screen, which is rarely what you want. Use a boolean comparison instead: count > 0 && <Component />.

3. if/else Statements or Variables When your logic gets complex, pull it out of the JSX. Nested ternaries are hard to read and maintain. Assign the resulting JSX to a variable and render that variable.

let content;
if (status === 'loading') {
  content = <Spinner />;
} else if (status === 'error') {
  content = <ErrorMessage />;
} else {
  content = <Dashboard data={data} />;
}

return <main>{content}</main>;

In an interview, explaining the trade-offs between these three patterns is a strong signal. It shows you think about maintainability, not just making the code work. Ternaries are concise but can become unreadable. if/else is verbose but clear for complex logic.

Try it

Build a simple Accordion component. It should have a title that is always visible and a block of content text. Clicking the title should toggle the visibility of the content. This exercise requires one piece of state, one event handler, and one conditional render.

Next: Rendering Lists & Basic useEffect

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Managing Component State with useState

Next

Rendering Lists & Basic useEffect