Sub topic 14
Adding your own component
This chapter covers the step where you stop reading the generated code and start changing it. You will replace the template's App with your own, add a stateful Counter component, and watch hot updates in the browser.
Prerequisites
This chapter assumes the following:
- You have scaffolded a project with
npm create vite@latest my-app -- --template reactand runnpm install. - The dev server is running with
npm run dev, usually athttp://localhost:5173. - You know JavaScript functions, destructuring, arrow functions and ES modules (
importandexport). - You have seen the basic ideas of JSX, props and state from earlier chapters.
What you will build
You will build two files. Counter.jsx holds a component that remembers a number. App.jsx renders that component inside ordinary markup and passes it a prop. The entry file src/main.jsx stays unchanged. It already renders App into the #root element.
Step 1: Create the Counter component
Create src/Counter.jsx. A component is a function whose name starts with a capital letter and which returns JSX.
import { useState } from 'react'
function Counter({ label }) {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}
export default CounterEach line has a job:
Counter({ label })destructures the props object. React calls your function with one argument, an object holding every prop. Writing{ label }pulls out the one you need.useState(0)returns a pair. The first item is the current value, and the second is a function that updates it. The0is the initial value, used only on the first render.onClick={() => setCount(count + 1)}passes a function to the button. React calls it when the user clicks. Do not writeonClick={setCount(count + 1)}. That calls the setter during rendering, which causes an infinite loop of updates.{label}: {count}embeds JavaScript expressions in the markup. The colon between them is plain text.export default Counterlets other files import the component with any local name.
Step 2: Use it from App
Open src/App.jsx. Replace its contents with this:
import Counter from './Counter.jsx'
function App() {
return (
<main>
<h1>My first React app</h1>
<Counter label="Clicks" />
</main>
)
}
export default AppSave the file. The browser updates without a manual reload, and you see a heading and a button that reads Clicks: 0. Click the button and the number increases.
Two details are worth noting:
- The import path includes the file extension and starts with
./. Vite resolves extensionless imports too, but writing.jsxkeeps the path explicit and matches the template's ownimport App from './App.jsx'. label="Clicks"is a string literal. For anything that is not a string, use braces, as in<Counter label={'Clicks'} />or<Counter start={5} />.
Step 3: Watch hot module replacement
With the dev server running, edit the heading text in App.jsx and save. The page changes in place. This is hot module replacement (HMR). Vite sends only the changed module to the browser, and the React plugin's fast refresh swaps the component while keeping its state where it can.
Try this experiment:
- Click the button until it shows
Clicks: 3. - Change
label="Clicks"tolabel="Taps"and save. - The button now reads
Taps: 3.
The count survived because fast refresh re-ran the App function with new props and kept the state of the Counter that was already mounted. Now change something inside Counter.jsx, such as the initial value in useState(0). Fast refresh may reset that component's state, or keep it, depending on the edit. This is expected. The initial value is only read on the first render, so a kept state will not show the new initial value until you reload.
Step 4: Reuse the component
State belongs to each component instance, not to the component definition. Render Counter three times to see this:
import Counter from './Counter.jsx'
function App() {
return (
<main>
<h1>My first React app</h1>
<Counter label="Clicks" />
<Counter label="Likes" />
<Counter label="Shares" />
</main>
)
}
export default AppEach button counts on its own. React tracks the instances by their position in the tree, so three Counter elements give three separate pieces of state. The prop makes each one look different, and the state makes each one behave independently.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Failed to resolve import "./Counter.jsx"` | The file is misnamed or in another folder | Check that `Counter.jsx` sits next to `App.jsx` and that the case matches exactly |
| Browser shows `<counter>` as an unknown element, and nothing renders | The component name starts with a lowercase letter | Name components with an initial capital: `Counter`, not `counter` |
| `Too many re-renders` error | A setter is called during render, as in `onClick={setCount(1)}` | Pass a function: `onClick={() => setCount(1)}` |
| `Adjacent JSX elements must be wrapped` | A component returns two siblings with no parent | Wrap them in a parent element or in a fragment, `<>...</>` |
| `Counter` is `undefined` or `Element type is invalid` | The file uses `export default` but you imported with braces, or the reverse | Match the style: `import Counter from` for a default export |
| Count does not change after a click | State was mutated directly, for example `count++` | Call the setter: `setCount(count + 1)` |
Edge cases to know about
Several updates in one handler
State updates are queued, and count holds the value from the current render. This handler adds only 1, not 3:
function handleClick() {
setCount(count + 1)
setCount(count + 1)
setCount(count + 1)
}Each call reads the same count. When the new value depends on the previous one, pass an updater function instead:
function handleClick() {
setCount((c) => c + 1)
setCount((c) => c + 1)
setCount((c) => c + 1)
}This version adds 3 because each updater receives the latest queued value.
StrictMode and double rendering
The template wraps App in <StrictMode>. In development, React renders components twice to expose impure code. If you add a console.log to the body of Counter, you will see it print twice per render. This does not happen in the production build, and it does not mean your component renders twice for the user.
Components must not be defined inside components
Declaring function Counter inside App creates a new component type on every render. React then treats it as a different component and discards its state each time. Define components at the top level of a module, as Counter.jsx does.
Putting it together
The workflow in this chapter is the one you will repeat in every React project:
- Make a new file for the component and export it.
- Import it where you want to use it.
- Pass data in as props.
- Keep data that changes over time in state, inside the component that owns it.
- Save and let HMR show the result.
Exercise
You add <Counter label="Likes" /> below an existing <Counter label="Clicks" />. You click the first button twice. What do the two buttons show, and why? Then explain what changes if you replace onClick={() => setCount(count + 1)} with onClick={setCount(count + 1)}.
Show answer
The buttons show Clicks: 2 and Likes: 0. Each Counter instance has its own state, so a click on one does not affect the other. With onClick={setCount(count + 1)}, the setter runs during rendering instead of on click. That schedules another render, which calls the setter again, and React stops with a "Too many re-renders" error. The handler must be a function, such as () => setCount(count + 1).
Exercise
A handler calls setCount(count + 1) twice in a row, and the count goes up by 1 per click. Rewrite the handler so one click adds 2.
Show answer
Use updater functions: setCount((c) => c + 1) followed by setCount((c) => c + 1). Each updater receives the latest queued value, so the two updates add up to 2. The original version reads the same count from the current render both times.