Wednesday, June 24, 2026

React State and Hooks: Building Interactive Applications

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.

  1. Accessing DOM elements directly

function AutoFocusInput() {

  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus(); // focus the input on mount
  }, []);

  return <input ref={inputRef} placeholder="I'm focused automatically!" />;
}
  1. 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)

function ProductList({ products, filterText }) {
  // This runs on EVERY render, even when filterText hasn't changed
   
  const filtered = products.filter(p =>
    p.name.toLowerCase().includes(filterText.toLowerCase())
  );

  return <ul>{filtered.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}

With useMemo (solution)

import { useMemo } from 'react';

function ProductList({ products, filterText }) {
  // Only recalculates when `products` or `filterText` changes
  const filtered = useMemo(() =>
    products.filter(p =>
      p.name.toLowerCase().includes(filterText.toLowerCase())
    ),
    [products, filterText]
  );

  return <ul>{filtered.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}


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

function SearchPage() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  // Stable function reference — won't cause SearchBar to re-render on unrelated state changes
  const handleSearch = useCallback(async (searchQuery) => {
    const data = await fetch(`/api/search?q=${searchQuery}`).then(r => r.json());
    setResults(data);
  }, []); // no deps needed — doesn't close over any changing values

  return (
    <div>
      <SearchBar onSearch={handleSearch} />
      <ResultsList results={results} />
    </div>
  );
}


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

const [state, dispatch] = useReducer(reducer, initialState);

Counter example

import { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + action.payload };
    case 'decrement': return { count: state. count - action.payload };
    case 'reset':     return initialState;
    default:          throw new Error(`Unknown action: ${action.type}`);
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment', payload: 1 })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement', payload: 1 })}>-</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </div>
  );
}


Key Takeaways

HookWhat it does When to use it
useState                    Holds reactive dataAny value that should update the UI

useEffect

Runs side effects             

Data fetching, subscriptions, timers

useRef

Mutable container, no re-render  

DOM access, storing interval IDs

useMemo

Memoizes a computed value

Expensive calculations on large data

useCallback

Memoizes a function                   

Stable callbacks passed to child components
useReducer
Complex state with actions
Multi-field state, state machines

useContextReads from a contextAuth state, theme, global settings

useLayoutEffect        

Like useEffect, but before paint            

DOM measurements, preventing flicker


Practice Exercises

  1. Stopwatch — Start, stop, and reset using setInterval inside useEffect
  2. Character Counter — Show remaining chars as a user types in a <textarea>
  3. Filtered Todo List — Add categories and an "All / Active / Done" filter
  4. 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. 

1 comment:

Advanced React Concepts for Beginners: Conditional Rendering, Context API & Custom Hooks (2026 Guide)

Advanced React Concepts: A Practical Guide React has evolved significantly over the years, and mastering its advanced concepts is essential ...