Quick Recap
Before we dive in, here's what you should already know from Part 1:
- React apps are built from components — JavaScript functions that return JSX
- JSX lets you write HTML-like syntax inside JavaScript
- Props pass data from a parent component down to a child
Now we're going one step further: making your UI actually respond to users.
Why Your App Needs State
Static HTML is great for content that never changes. But real applications need to react — pun intended — to what the user does:
- A form that validates as you type
- A shopping cart that updates on item add
- A dark mode toggle that changes the entire UI
- Live data refreshing from a server
All of this is powered by the state. Let's build the foundation.
Functions in React: A Quick Primer
React is function-first. You'll use three styles constantly:
Function Declaration
function Welcome(props) {
return <h1>Welcome, {props.name}</h1>;
}
Arrow Function (most common in modern React)
const Welcome = ({ name }) => <h1>Welcome, {name}</h1>;
Callback Functions
A callback is a function passed as an argument to another function, called later. In React, every event handler is a callback:
function Button() {
const handleClick = () => console.log('Clicked!');
return <button onClick={handleClick}>Click me</button>;
}
Props vs. State
This is the most important mental model in React. Get this right, and everything else clicks.
| Props | State | |
|---|---|---|
| Defined by | Parent component | Component itself |
| Mutable? | No — read-only | Yes — via setter |
| Analogy | Function argument | Variable inside the function |
| Triggers re-render? | When the parent re-renders | Yes, on every change |
Props in practice
// Parent passes data down
function App() {
return <Greeting name="Alice" age={25} />;
}
// Child receives it via destructuring
function Greeting({ name, age }) {
return (
<div>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
</div>
);
}
The useState Hook
useState is how you add reactive data to a component. When state changes, React automatically re-renders.
Syntax
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
// ^value ^setter ^initial value
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Multiple state variables
function UserProfile() {
const [name, setName] = useState('');
const [age, setAge] = useState(0);
const [isLoggedIn, setIsLoggedIn] = useState(false);
// ...
}
⚠️ Common mistakes
1. Mutating state directly
// ❌ Wrong — React won't detect these changes.push('banana');
setItems(items);
// ✅ Correct — always create a new array/object
setItems([...items, 'banana']);
2. Reading the state immediately after setting it
// ❌ Still shows old value
setCount(count + 1);
console.log(count);
// ✅ Use useEffect to respond to changes
useEffect(() => {
console.log('Count is now:', count);
}, [count]);
3. Stale state in rapid updates
// ❌ Only increments once — both reads see the same `count`
setCount(count + 1);
setCount(count + 1);
// ✅ Use functional update — reads the latest value
setCount(prev => prev + 1);
setCount(prev => prev + 1);
Event Handling
onClick
function ClickExample() {
const [message, setMessage] = useState('Click the button!');
return (
<div>
<p>{message}</p>
<button onClick={() => setMessage('Clicked!')}>Click Me</button>
</div>
);
}
onChange
function InputExample() {
const [text, setText] = useState('');
return (
<div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type something..."
/>
<p>You typed: {text}</p>
</div>
);
}
onSubmit
function FormExample() {
const [input, setInput] = useState('');
const handleSubmit = (e) => {
e.preventDefault(); // prevents page refresh
console.log('Submitted:', input);
setInput('');
};
return (
<form onSubmit={handleSubmit}>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button type="submit">Submit</button>
</form>
);
}
Passing arguments to the handler
function ButtonGroup() {
const handleClick = (id) => console.log('Clicked:', id);
return (
<div>
<button onClick={() => handleClick('btn1')}>Button 1</button>
<button onClick={() => handleClick('btn2')}>Button 2</button>
</div>
);
}
Controlled Components & Forms
In React, form inputs should be controlled — meaning their value is driven by state, not the DOM.
Multi-field form pattern
function RegistrationForm() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({ ...prev, [name]: value }));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form data:', formData);
};
return (
<form onSubmit={handleSubmit}>
<input name="username" value={formData.username} onChange={handleChange} placeholder="Username" />
<input name="email" value={formData.email} onChange={handleChange} placeholder="Email" />
<input name="password" type="password" value={formData.password} onChange={handleChange} placeholder="Password" />
<button type="submit">Register</button>
</form>
);
}
The key pattern: a single handleChange function handles all fields, using the name attribute as the key.
The useEffect Hook
useEffect handles side effects — anything that reaches outside the component:
- Fetching data from an API
- Setting up timers or subscriptions
- Listening to DOM events
- Reading/writing localStorage
The dependency array controls when the effect runs
// Runs after every render
useEffect(() => { ... });
// Runs once on mount
useEffect(() => { ... }, []);
// Runs when `count` changes
useEffect(() => { ... }, [count]);
// Runs when `count` OR `name` changes
useEffect(() => { ... }, [count, name]);
Fetching data on the mount
function DataFetcher() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(json => {
setData(json);
setLoading(false);
});
}, []); // Empty array = run once
if (loading) return <p>Loading...</p>;
return <div>{/* render data */}</div>;
}
Cleanup functions
Always clean up effects that set up subscriptions, timers, or event listeners — otherwise you'll get memory leaks:
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
return () => clearInterval(interval); // cleanup on unmount
}, []);
return <p>Elapsed: {seconds}s</p>;
}
function WindowTracker() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize); // cleanup
}, []);
return <p>Window width: {width}px</p>;
}
The useRef Hook
useRef gives you a mutable container that persists across renders — but changing it does not trigger a re-render. It has two main uses.
- Accessing DOM elements directly
const inputRef = useRef(null);
useEffect(() => { inputRef.current.focus(); // focus the input on mount }, []);
return <input ref={inputRef} placeholder="I'm focused automatically!" />;}- Storing values that shouldn't trigger re-renders
function StopWatch() { const [time, setTime] = useState(0); const intervalRef = useRef(null); // store the interval ID without re-rendering
const start = () => { intervalRef.current = setInterval(() => setTime(t => t + 1), 1000); };
const stop = () => clearInterval(intervalRef.current);
return ( <div> <p>{time}s</p> <button onClick={start}>Start</button> <button onClick={stop}>Stop</button> </div> );}
The useMemo Hook
useMemo memorizes the result of a computation — it only recalculates when its dependencies change. Use it when you have an expensive calculation that shouldn't re-run on every render.
Without useMemo (problem)
With useMemo (solution)
The useCallback Hook
useCallback memoizes a function itself — it returns the same function reference across renders unless its dependencies change.
Why this matters
In React, every render creates new function instances. If you pass a function as a prop to a child component, the child sees a "new" function every time and re-renders unnecessarily.
function Parent() {
const [count, setCount] = useState(0);
// ❌ New function instance on every render
const handleClick = () => console.log('clicked');
// ✅ Same reference unless dependencies change
const handleClick = useCallback(() => {
console.log('clicked');
}, []); // no dependencies = created once
return <ExpensiveChild onClick={handleClick} />;
}
Real-world example: search handler
The useReducer Hook
useReducer is an alternative to useState for managing complex state logic. Instead of calling a setter directly, you dispatch actions that a reducer function handles.
Think of it as a mini Redux inside your component.
Syntax
Counter example
Key Takeaways
| Hook | What it does | When to use it |
|---|---|---|
useState | Holds reactive data | Any value that should update the UI |
| Runs side effects | Data fetching, subscriptions, timers |
| Mutable container, no re-render | DOM access, storing interval IDs |
| Memoizes a computed value | Expensive calculations on large data |
| Memoizes a function | Stable callbacks passed to child components |
useReducer | Complex state with actions | Multi-field state, state machines |
useContext | Reads from a context | Auth state, theme, global settings |
| Like useEffect, but before paint | DOM measurements, preventing flicker |
Practice Exercises
- Stopwatch — Start, stop, and reset using
setIntervalinsideuseEffect - Character Counter — Show remaining chars as a user types in a
<textarea> - Filtered Todo List — Add categories and an "All / Active / Done" filter
- Login Form Validation — Real-time feedback on email format and password length
Have questions or want to share what you built? Drop a comment below.

hi
ReplyDelete