Sub topic 14
Adding your own component
This chapter assumes you have already scaffolded a Vite React project and have the dev server running. You should also know what JSX, props and useState are. Here you will replace the starter content with your own component and watch hot module replacement (HMR) update the page.
Plan the change
The goal is a small Counter component that App renders. It combines three ideas from earlier chapters: a component, a prop and state.
Create the component
Create src/Counter.jsx. Component file names and function names start with a capital letter. React treats a lowercase tag such as <counter> as a built-in HTML element, not as your component.
import { useState } from 'react'
function Counter({ label }) {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}
export default Counterlabel arrives as a prop and is read-only. count is state owned by this component. Calling setCount schedules a re-render, and React runs the function again with the new value.
Use it in App
Replace the contents of src/App.jsx.
import Counter from './Counter.jsx'
function App() {
return (
<main>
<h1>My first React app</h1>
<Counter label="Clicks" />
</main>
)
}
export default AppSave both files. The browser updates without a manual reload. Click the button a few times, then change "Clicks" to "Taps" and save. The label changes, and in most cases the count stays. That is HMR with fast refresh keeping component state across an edit.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Overlay says it failed to resolve the import | Wrong path or missing extension | Use `./Counter.jsx` and match the file name's case |
| Nothing renders, or a warning about an unknown tag | Lowercase component name | Rename to `Counter` |
| JSX inside a `.js` file fails to parse | Wrong file extension | Rename the file to `.jsx` |
| Count never changes | State mutated directly, such as `count++` | Call `setCount` |
| Adjacent elements error | Component returns two root elements | Wrap them in one element or a fragment `<>...</>` |
Check your understanding
Exercise
You add a second line, <Counter label="Likes" />, under the first one in App. Do the two buttons share one count? Why or why not?
Show answer
No. Each rendered Counter gets its own state from its own useState call, so clicking one button does not change the other. Sharing a value would require moving the state up into App and passing it down as props.
Exercise
You rename the file to counter.jsx but still write import Counter from './Counter.jsx'. On a case-insensitive file system it may work locally. What can happen in a production build on Linux?
Show answer
The import can fail to resolve because Linux file systems are case-sensitive. The file name in the import must match the real file name exactly.