Show different things depending on state, with a ternary, with &&, and with an early return. Click Log in and watch the page change.
React · beginner · 7 min · 13 steps · free
import { useState } from 'react';
function Inbox({ count }) {
if (count === 0) {
return <p>No new messages.</p>;
}
return <p>You have {count} new messages.</p>;
}
export default function App() {
const [loggedIn, setLoggedIn] = useState(false);
return (
<div>
{loggedIn ? <Inbox count={3} /> : <p>Please log in.</p>}
<button onClick={() => setLoggedIn(!loggedIn)}>
{loggedIn ? 'Log out' : 'Log in'}
</button>
{loggedIn && <small>Signed in as Ada</small>}
</div>
);
}<App> for the first time: it calls the App function.useState runs for the first time, so React stores the starting value for loggedIn and returns it: false.loggedIn is false, so the ternary picks <p>Please log in.</p>, and loggedIn && … adds nothing.onClick runs.setLoggedIn(!loggedIn) does not change loggedIn right away: React queues the update and will render again. In this call loggedIn is still false.<App> again (render 2): it calls App once more, from the top.useState returns the value React has kept for loggedIn: true. The starting value is only used on the first render.loggedIn is true: the ternary picks <Inbox count={3} />, the button says "Log out", and && adds the <small> line.count === 0 is false, so the early return is skipped.Inbox returns JSX: a description of what the screen should show, <p>You have 3 new messages.</p>. React has not changed the page yet.Answer: Nothing. false renders nothing.
Answer: 0. 0 is a number, and React renders numbers.
← Composition with children · Rendering Lists with Keys →