Adapting the Interface: Conditional Rendering with State and Props

Learn how components use internal memory (state) and data from parents (props) to decide what to show on the screen.

Let's build an adaptable UI. We'll start with a component that needs to remember if a user is logged in.

<LoginStatus />

What is State? The Component's Memory

State is a component's private memory. It's where you store data that can change over time, such as user input, API data, or a UI toggle. You add state to a component with the useState hook, which returns a state variable and a function to update it.

What are Props? Passing Data Down

Props (short for properties) are used to pass data from a parent component down to a child component. This flow is one-way and makes components reusable and configurable. A child component receives props as an object and cannot modify them directly.

State-Driven UI: Reacting to Change

When you update a state variable using its setter function (e.g., setIsLoggedIn(true)), React automatically re-renders the component. Your conditional logic then re-evaluates, showing the updated UI. This is the core mechanism for creating interactive user interfaces.

Props-Driven UI: Configuring Components

A child component can use the props it receives to render conditionally. For instance, a <Button variant="primary" /> component can use the variant prop to apply different CSS classes, changing its appearance based on what the parent component decides.

Practice Zone


Interactive Test 1: State vs. Props

Match the concept to its correct description in a React component.

Arrastra en el orden correspondiente.


Arrastra las opciones:

function User({ name }) {...}
const [count, setCount] = useState(0);

Completa el código:

Internal, changeable memory______
Data from a parent______
Unlock with Premium

Interactive Test 2: Complete the State Logic

Rellena los huecos en cada casilla.

import React, { useState } from 'react';

function LoginButton() {
  const [, ] = useState(false);

  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome back!</p>
      ) : (
        <button onClick={() => setIsLoggedIn(true)}>Log in</button>
      )}
    </div>
  );
}
Unlock with Premium

Practice Example: A Props-Based Component

Create a component named `Alert` that accepts a `status` prop. If `status` is "error", it should display a red "Error!" message. Otherwise, it should show a green "Success!" message.

Enunciado:

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

function Alert({ status }) { return ( <div> {status === 'error' ? <p style={{color: 'red'}}>Error!</p> : <p style={{color: 'green'}}>Success!</p>} </div> ); }

Unlock with Premium

Knowledge Check

What triggers a React component to re-render?


Unlock with Premium

State and Props in Action

State and props are the pillars of dynamic React applications. Understanding their interplay is key to building complex, interactive components.


1. State: The Source of Truth

State is data that is owned and managed *inside* a single component. When this data needs to change due to user interaction (like clicking a button or typing in a form), you use the state setter function to trigger a re-render with the new value.

function Counter() {
  const [count, setCount] = useState(0);

  return <button onClick={() => setCount(c => c + 1)}>
    Clicked {count} times
  </button>
}

2. Props: Configuring Child Components

Props allow you to make your components reusable. A parent component passes data down, and the child component uses that data to render. The child should not modify its props—this is known as "top-down" data flow.

// Parent
<UserProfile user={{ name: 'Alex', avatar: '...' }} />

// Child: UserProfile.js
function UserProfile({ user }) {
  return <div>
    <img src={user.avatar} />
    <p>{user.name}</p>
  </div>
}

Alex

3. Combining State and Props

Often, a parent component will hold state and pass it down as props to multiple children. When the parent's state updates, all children receiving that data as a prop will re-render with the new information. This pattern allows you to keep your state in one place and have the UI react consistently.

const [isLoggedIn, setIsLoggedIn] = useState(false);
// ...
<Navbar isLoggedIn={isLoggedIn} />
<MainContent isLoggedIn={isLoggedIn} />
Both Navbar and MainContent will update when `isLoggedIn` changes.

Practical Takeaway: Use state for data that changes *within* a component. Use props to pass data *into* a component to customize its behavior and content.

State & Props Glossary

State
A JavaScript object that stores a component's private data. State is managed within the component and can change over time. When state changes, the component re-renders.
Props (Properties)
Read-only data passed from a parent component to a child component. Props are the primary way to configure and customize child components.
`useState` Hook
A built-in React Hook that lets you add state to functional components. It returns an array with two elements: the current state value and a function to update it.
Re-render
The process where React executes a component's code again to calculate and apply UI updates to the DOM. It's automatically triggered by a change in state or props.
Data Flow
In React, data flows in one direction: from parent to child components (top-down). A child cannot directly modify the props it receives from its parent.