Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 10 of 10
Practice & Quiz - React Foundations
Test your React fundamentals with a practical interactive counter exercise and 5 quiz questions covering the Virtual DOM, JSX rules, useState, and component design.
Practical Exercise - Stateful Counter with Reset
import { useState } from 'react';
// Build a counter that demonstrates the useState snapshot model
// Key concepts: functional updater, lazy init, derived state
interface CounterProps {
initialValue?: number;
step?: number;
max?: number;
}
function Counter({ initialValue = 0, step = 1, max = 10 }: CounterProps) {
// Lazy initializer - only runs once on mount
const [count, setCount] = useState(() => {
const saved = localStorage.getItem('counter');
return saved ? parseInt(saved, 10) : initialValue;
});
// Derived state - NOT stored in useState
const isAtMax = count >= max;
const progress = Math.round((count / max) * 100);
const increment = () => {
// Functional updater - safe even if called multiple times
setCount(prev => {
const next = Math.min(prev + step, max);
localStorage.setItem('counter', String(next));
return next;
});
};
const reset = () => {
setCount(initialValue);
localStorage.removeItem('counter');
};
return (
<div style={{ padding: '1rem', border: '1px solid #ccc', borderRadius: 8 }}>
<h2>Count: {count}</h2>
<progress value={progress} max={100} style={{ width: '100%' }} />
<p>{progress}% of max ({max})</p>
<button onClick={increment} disabled={isAtMax}>
+{step}
</button>
<button onClick={reset} style={{ marginLeft: 8 }}>
Reset
</button>
{isAtMax && <p style={{ color: 'red' }}>Maximum reached!</p>}
</div>
);
}
export default function App() {
return <Counter initialValue={0} step={2} max={10} />;
}
// Build: npm create vite@latest counter-app -- --template react-ts
// Then replace src/App.tsx with this codeModule Quiz
JSX compiles `<div className='box'>Hi</div>` into what?
Tip
Tip
Practice Practice Quiz React Foundations in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Modern React: Use Hooks instead of class lifecycle methods
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz React Foundations from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz React Foundations is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?