Anatomy of a modern react component
1. Imports
What the component depends on.
1
2
import { useState, useEffect, useMemo } from "react";
import "./Button.css"; // styles (or CSS-in-JS)
2. The Function component
1
function Button({ label, disabled = false, onClick }) {
- Props are just function arguments
- Destructuring is standard
- Default values inline
3. Hooks (top-level, always)
1
2
3
4
5
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Mounted or updated");
}, [count]);
Full Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { useState, useMemo } from "react";
export default function Counter({ initial = 0 }) {
const [count, setCount] = useState(initial);
const isEven = useMemo(() => count % 2 === 0, [count]);
const increment = () => {
setCount((c) => c + 1);
};
return (
<div>
<p>Count: {count}</p>
<p>{isEven ? "Even" : "Odd"}</p>
<button onClick={increment}>+</button>
</div>
);
}
This post is licensed under CC BY 4.0 by the author.