A component defined inside another loses its state
Both counters were at 1. Switching the theme re-rendered App, which created a new InnerCounter function, so React threw the old one away and its count went back to 0. Counter, declared at the top level, kept its count. (useState is covered in Topic 4.2.)
A component is a JavaScript function whose name starts with a capital letter and which returns JSX; once defined, you use it like a new HTML tag, as many times as you want, and you always define it at the top level of a file, never inside another component.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a Logo component that returns an <h1> with the text Hectal and use it twice inside App.
This code shows nothing. Find and fix the bug:
``jsx
function Welcome() {
<h2>Welcome!</h2>;
}
Turn this into two components, Header and App, so the header markup lives in its own component:
``jsx
function App() {
return (
<main>
<header><h1>Recipes</h1><p>Cook something new</p></header>
<p>Pick a recipe below.</p>
</main>
);
}
Explain it without notes
What is a function component, and what rules must its name follow?
What can a component return? What happens if it returns undefined?
Why should you never define a component inside another component?
What is the difference between <Planet />, {Planet} and {Planet()} in JSX?
Preview
Console
Nothing logged yet.Expected console output
After two clicks: outer: 1 | inner: 1
After theme switch: outer: 1 | inner: 0