React Architecture: Mastering State and Props in Class vs. Functional Components
Compare React class components with function components and Hooks by building one counter both ways. You see how each reads props, stores state and handles events, why useState replaces instead of merging, how stale closures happen, when to use lazy initial state, and how a custom Hook shares logic. Both counters and the custom Hook were run with React 19.

React components can be written as classes or as functions with Hooks. This guide is for developers who write new code with functions but still meet class components in older codebases. You will build the same counter both ways and see how each one reads props, stores state and handles events. Then you will fix three common bugs that appear when code moves from one style to the other.
This is part 19 of the Frontend & JavaScript Fundamentals series. It follows getting started with React, JSX and components, which introduced props.
Key takeaways
- react.dev recommends function components for new code. Class components still work, so you need to read them in older apps.
this.setStatemerges an object into state. AuseStatesetter replaces the value, so spread the old object yourself.- A function component sees the props and state of the render it came from. That avoids some class bugs but causes stale closures in timers.
Props and state in one sentence each
Props are the read-only inputs a parent passes to a component. State is a component's own memory, which it updates to change what it shows over time. react.dev's rule for props is short: don't try to change them. When something must change in response to user input, it belongs in state.
| Class component | Function component | |
|---|---|---|
| Read props | this.props.name |
Function argument, usually destructured: ({ name }) |
| Declare state | this.state = {...} in the constructor |
One useState call per value |
| Update state | this.setState(...) merges the object |
Setter replaces the value |
| Event handlers | Need bind or class-field arrow functions |
Plain functions inside the component |
| Share logic | Higher-order components or render props | Custom Hooks |
| Status | Supported, not recommended for new code | Recommended |
Props: this.props vs a function argument
In a class, props live on the instance, and you read them through this:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
The instance lives across renders, and React updates this.props and this.state on it. So code that runs later, such as a setTimeout callback, reads the latest values, not the ones from the render that scheduled it. Usually that is what you want, but sometimes it is a subtle bug.
In a function component, props are the function's single argument, so you destructure them:
const Welcome = ({ name }) => {
return <h1>Hello, {name}</h1>;
};
Each render is a separate call with its own name. Callbacks created during that render keep its values. react.dev's migration guide does exactly this: move the render body into a function and replace this.props with destructured props.
State: one object vs separate values
Class: one object, merged
A class keeps all state in one object. You set it in the constructor and update it with this.setState(). react.dev's Component reference says an object you pass is shallowly merged into this.state, so fields you leave out stay as they were.
// Initializing
this.state = {
count: 0,
status: 'active'
};
// Updating
this.setState({ count: this.state.count + 1 });
// 'status' remains 'active' automatically
Function: separate values, replaced
With useState, you usually declare one state variable per value:
const [count, setCount] = useState(0);
const [status, setStatus] = useState('active');
// Updating
setCount(prev => prev + 1);
prev => prev + 1 is an updater function. React passes in the pending state, so several updates in one event all count. Use it whenever the next value depends on the previous one. The same works in a class: this.setState(prevState => ...).
Build: the counter as a class
This counter takes a startValue prop and keeps the count and the last action in state:
import React, { Component } from 'react';
class CounterClass extends Component {
constructor(props) {
super(props);
// 1. Initialization
this.state = {
count: props.startValue || 0,
lastAction: 'none'
};
// 2. Binding methods (The "this" headache)
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
increment() {
// 3. Merging state
this.setState((prevState) => ({
count: prevState.count + 1,
lastAction: 'increment'
}));
}
decrement() {
this.setState((prevState) => ({
count: prevState.count - 1,
lastAction: 'decrement'
}));
}
render() {
return (
<div className="p-6 border rounded-lg shadow-sm">
<h3>Class Counter</h3>
<p>Start Value (Prop): {this.props.startValue}</p>
<div className="text-4xl font-bold my-4">
{this.state.count}
</div>
<p className="text-gray-500 mb-4">Last Action: {this.state.lastAction}</p>
<div className="flex gap-2">
<button onClick={this.decrement} className="px-4 py-2 bg-red-500 text-white rounded">-</button>
<button onClick={this.increment} className="px-4 py-2 bg-blue-500 text-white rounded">+</button>
</div>
</div>
);
}
}
export default CounterClass;
What to notice:
- Constructor: react.dev says you must call
super(props)before any other statement in it. - Binding: without
bind,thisisundefinedwhen React callsincrementfrom the click. Class-field arrow functions (increment = () => {...}) are the other common fix. - Spread-out logic: the state lives in the constructor, the updates in methods, and the output in
render.
Build: the counter as a function
The same counter with Hooks:
import React, { useState } from 'react';
const CounterFunctional = ({ startValue = 0 }) => {
// 1. Isolated State Slices
const [count, setCount] = useState(startValue);
const [lastAction, setLastAction] = useState('none');
const increment = () => {
setCount(prev => prev + 1);
setLastAction('increment');
};
const decrement = () => {
setCount(prev => prev - 1);
setLastAction('decrement');
};
return (
<div className="p-6 border rounded-lg shadow-sm">
<h3>Functional Counter</h3>
<p>Start Value (Prop): {startValue}</p>
<div className="text-4xl font-bold my-4">
{count}
</div>
<p className="text-gray-500 mb-4">Last Action: {lastAction}</p>
<div className="flex gap-2">
<button onClick={decrement} className="px-4 py-2 bg-red-500 text-white rounded">-</button>
<button onClick={increment} className="px-4 py-2 bg-blue-500 text-white rounded">+</button>
</div>
</div>
);
};
export default CounterFunctional;
What to notice:
- No constructor: state is declared inline and the code reads top to bottom.
- No binding:
incrementis a closure inside the component, so it can seesetCountdirectly. - Default prop:
startValue = 0applies when the prop is missing orundefined. react.dev notes it does not apply tonullor0. - Grouping:
countandlastActionalways change together. react.dev's advice for that case is to consider one state variable, such as{ count, lastAction }. They are split here only to mirror the class version.
Three bugs to watch for
1. Stale closures
react.dev calls state a snapshot: a state variable's value never changes within a render, even inside async code started from it. A timer created during a render keeps that render's count.
// Avoid: uses the count from the render that set the timer,
// so clicks made during the delay are lost
const incrementLater = () => {
setTimeout(() => setCount(count + 1), 1000);
};
// Prefer: an updater function always gets the latest value
const incrementLaterSafe = () => {
setTimeout(() => setCount(prev => prev + 1), 1000);
};
If you need to read the latest value without updating it, store it in a ref with useRef, or list it in your effect's dependency array.
2. Merge vs replace
this.setState merges. A useState setter replaces the whole value. This is the classic bug when a class form moves to a function. react.dev's state structure guide shows the fix: copy the other fields with a spread.
const [form, setForm] = useState({ name: '', email: '' });
// Avoid: drops `email`
setForm({ name: 'Ada' });
// Prefer: keeps every other field
setForm(prev => ({ ...prev, name: 'Ada' }));
3. Slow initial state
A class constructor runs once. In a function component, useState(expensiveComputation()) calls expensiveComputation on every render. react.dev says React ignores the result after the first render, but the work still happens. Pass a function instead, and React calls it only on the first render (twice in Strict Mode during development, to help you spot impure code):
// Only runs once
const [value, setValue] = useState(() => expensiveComputation());
Which style should you use?
Write new components as functions, as react.dev recommends. The practical win is reuse. In a class codebase, sharing the counter logic needed a higher-order component or a render prop. With Hooks, you extract it into a custom Hook:
import { useState } from 'react';
function useCounter(start = 0) {
const [count, setCount] = useState(start);
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => prev - 1);
return { count, increment, decrement };
}
react.dev points out that a custom Hook shares stateful logic, not the state itself. Two components that call useCounter() each get their own count.
Still learn to read classes. Older apps are full of them, and react.dev's Component reference shows how to migrate one step at a time. One caution: componentDidMount and componentDidUpdate are not a good model for useEffect. react.dev's guide on effects says to think of each effect as starting and stopping a synchronization, not as mount and update events.
Next in the series, React Hooks and custom Hook creation builds on useCounter with a fuller custom Hook.
Frequently asked questions
Are class components deprecated in React?
No. react.dev says class components are still supported, but it doesn't recommend them for new code. Existing class components keep working, and you can migrate them one at a time.
Why doesn't useState merge objects like setState?
A useState setter stores exactly the value you pass. If that value is an object with one field, the old fields are gone. Spread the previous object, setForm(prev => ({ ...prev, name })), or split the fields into separate state variables.
What is a stale closure in React?
It is a function that still sees state from an earlier render. Timers and callbacks capture the values of the render that created them, as react.dev's "State as a Snapshot" page explains. Use an updater function to change state, or a ref to read the latest value.
When should I use lazy initial state?
Use it when computing the starting value is expensive, for example parsing a large stored JSON string. Pass a function, useState(() => compute()), and React calls it only on the first render. For cheap values like 0 or '', a plain value is fine.
Can class and function components live in the same app?
Yes. A function component can render a class component and the other way round, and both receive props the same way from the parent's side. That is what makes a gradual migration possible.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead



Comments
Loading comments...