Fundamentals
1 min readRapid overview
React Fundamentals
Core React concepts for modern function component apps.
Table of Contents
- Components and JSX
- Props and State
- Events and Forms
- Lists and Keys
- Effects and Lifecycle
- Composition and Lifting State
Components and JSX
function Welcome() {
return <h1>Hello, React</h1>;
}
function App() {
return (
<main>
<Welcome />
</main>
);
}
Components are functions that return UI. JSX is compiled to React.createElement calls.
Props and State
function Counter({ initial }) {
const [count, setCount] = React.useState(initial);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
Props flow in, state is owned by the component and updated with setters.
Events and Forms
function SearchBox() {
const [value, setValue] = React.useState('');
return (
<input
value={value}
onChange={(event) => setValue(event.target.value)}
placeholder="Search"
/>
);
}
Use controlled inputs to keep form values in React state.
Lists and Keys
function TodoList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.label}</li>
))}
</ul>
);
}
Keys must be stable and unique for React to reconcile lists efficiently.
Effects and Lifecycle
function UserProfile({ userId }) {
const [user, setUser] = React.useState(null);
React.useEffect(() => {
let isActive = true;
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => {
if (isActive) setUser(data);
});
return () => {
isActive = false;
};
}, [userId]);
return user ? <div>{user.name}</div> : <span>Loading...</span>;
}
Use effects for data fetching, subscriptions, and manual DOM work.
Composition and Lifting State
function FilterableList({ items }) {
const [query, setQuery] = React.useState('');
const visible = items.filter((item) => item.label.includes(query));
return (
<section>
<SearchInput query={query} onChange={setQuery} />
<TodoList items={visible} />
</section>
);
}
function SearchInput({ query, onChange }) {
return (
<input value={query} onChange={(event) => onChange(event.target.value)} />
);
}
Lift shared state to the closest common parent so multiple children can read or update it.