gitmyhub

hooks-perf-issues

JavaScript ★ 14 updated 7y ago

This repo demonstrates a situation where it is slower to use React hooks than classes

A teaching demo showing how React hooks can make UI updates 4-5x slower than class components if callback functions aren't handled carefully.

JavaScriptReactsetup: easycomplexity 2/5

What This Repo Does

This repository demonstrates a real-world performance problem that can happen when building React applications with hooks. Specifically, it shows a situation where the same UI updates much slower when written with hooks compared to the older class-based approach — about 4-5 times slower, in fact. The repo isn't arguing that hooks are bad; it's a teaching tool that shows developers a pitfall they need to watch out for and manage carefully.

How It Works

The demo simulates a UI with nested components where clicking a button triggers a state change that ripples down through the component tree. When you run the hook version, clicking a button takes roughly 940-1090 milliseconds for that change to fully propagate. When you run the class version, the same interaction takes only 220-320 milliseconds.

The culprit is how hooks and classes handle callback functions differently. In the hook version, every time state changes, a new version of the callback function gets created, even though the function does the same thing. When a new callback is created, child components that are supposed to skip re-rendering (using React.memo) can't tell that the callback is functionally identical, so they re-render unnecessarily. Each re-render does expensive calculations, compounding the slowdown. In the class version, the callback stays the same in memory, so memoized components correctly skip their re-renders.

Who Would Use This

React developers building interactive applications would find this useful, especially anyone who's noticed their app feeling sluggish even though they tried to optimize. If you're working with complex component trees, deeply nested components, or components that do heavy calculations, this repo helps explain why performance might not be what you expect and points you toward solutions like being more careful about what dependencies you pass to hooks.

The repo is educational rather than a tool you'd integrate into your own project — it's meant to help you understand a specific pitfall so you can write faster React code from the start.

Where it fits