Migrating a Legacy React App from Class Components to Hooks: A Lead Engineer's Playbook
As a Lead Software Engineer, one of the larger pieces of work I've led is moving a production React application from class components to function components and hooks. This post describes the approach I recommend: incremental, test-first, and organised so the team keeps shipping features while the codebase gets better underneath.
Why migrate at all?
Class components still work, so "because hooks are newer" isn't a good enough reason. The real benefits are:
- Reusable logic. Custom hooks replace higher-order components and render props, which removes a lot of wrapper nesting.
- Related code stays together. Subscribing and unsubscribing live in one
useEffectinstead of being split acrosscomponentDidMountandcomponentWillUnmount. - Better TypeScript ergonomics. Typing props and hook return values is simpler than typing class generics and
this.state. - Hiring and onboarding. New developers learn React with hooks. A consistent codebase is faster to work in.
Rule #1: no big-bang rewrite
Rewriting everything on a long-lived branch is the fastest way to create merge conflicts, regressions and a frustrated team. Classes and hooks can live side by side, so migrate component by component, in normal-sized pull requests, alongside regular feature work.
A simple order that works well:
- Leaf components first: small presentational components with little or no state.
- Shared logic next: turn HOCs and render-prop components into custom hooks.
- Containers and pages last: by then the building blocks are already hooks.
- Opportunistic migration: if you touch a class component for a feature, migrate it in the same PR (when the change is small enough to review).
Rule #2: tests before refactoring
A refactor should not change behaviour, and the only way to prove that is with tests. Before migrating a critical screen, cover its main user flows with end-to-end tests. On my team this went hand in hand with introducing Cypress, which eventually reached more than 80% coverage. I wrote about that separately in how to reach 80%+ test coverage with Cypress.
Mapping lifecycle methods to hooks
| Class component | Function component |
|---|---|
this.state / setState | useState or useReducer |
componentDidMount | useEffect(() => {…}, []) |
componentDidUpdate (prop changed) | useEffect(() => {…}, [prop]) |
componentWillUnmount | cleanup function returned from useEffect |
shouldComponentUpdate | React.memo |
instance fields (this.timer) | useRef |
| HOC / render props | custom hook |
A typical before and after
Here is the pattern you'll see most often: a component that loads data when it mounts and when a prop changes.
class EmployeeList extends React.Component {
state = { employees: [], loading: true };
componentDidMount() {
this.load();
}
componentDidUpdate(prevProps) {
if (prevProps.teamId !== this.props.teamId) this.load();
}
async load() {
this.setState({ loading: true });
const employees = await api.getEmployees(this.props.teamId);
this.setState({ employees, loading: false });
}
render() {
if (this.state.loading) return <Spinner />;
return <ul>{this.state.employees.map((e) => <li key={e.id}>{e.name}</li>)}</ul>;
}
}
After the migration, the data logic moves into a reusable hook, and the component only renders:
function useEmployees(teamId) {
const [employees, setEmployees] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
setLoading(true);
api.getEmployees(teamId).then((data) => {
if (!cancelled) {
setEmployees(data);
setLoading(false);
}
});
return () => {
cancelled = true; // ignore responses for an old teamId
};
}, [teamId]);
return { employees, loading };
}
function EmployeeList({ teamId }) {
const { employees, loading } = useEmployees(teamId);
if (loading) return <Spinner />;
return <ul>{employees.map((e) => <li key={e.id}>{e.name}</li>)}</ul>;
}
Notice the cleanup flag: the class version had a hidden race condition (a slow response for an old
teamId could overwrite a newer one). Migrations are a good moment to fix bugs like this.
Common pitfalls
useStatedoes not merge.setStatein classes merged objects; the hook setter replaces the value. Split unrelated state into separateuseStatecalls, or useuseReducer.- Stale closures. Callbacks and effects see the values from the render they were created in. Use the functional updater (
setCount((c) => c + 1)) or a ref when you need the latest value. - Missing dependencies. An incomplete dependency array is the most common hooks bug. Let the linter tell you.
- Copying props into state. If a class used
getDerivedStateFromProps, the hooks version often doesn't need state at all: compute the value during render. - Over-memoising. Don't wrap everything in
useMemoanduseCallback. Add them where profiling or referential equality actually matters.
Make the rules automatic
A big part of leading a migration is making the right thing the easy thing. Enforce the hooks rules in ESLint so reviewers don't have to:
{
"plugins": ["react-hooks"],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}
On top of linting, a short pull-request checklist helps: behaviour unchanged? tests green? no new class components? Pairing a developer who has migrated many components with one who is new to hooks spreads the knowledge quickly.
Takeaways
- Migrate incrementally, in small PRs, alongside feature work.
- Protect critical flows with tests before you refactor them.
- Start with leaf components and shared logic; finish with containers.
- Automate the rules with ESLint, and use the migration to fix hidden bugs.
If your team in Slovenia or elsewhere is planning a React modernisation and you'd like someone who has led one, feel free to get in touch.