Urgent.News

What's breaking now, across thousands of outlets.

Tech

Making React Context Cheap with React Compiler

When building React apps, many developers have desired a context selector to optimize re-renders. However, React does not currently offer an API like `useContextSelector`, despite the performance impact of re-rendering numerous components due to context updates. This limitation existed even after React removed the `calculateChangedBits` function, which allowed components to listen for specific context changes.

Despite this, developers have attempted workarounds, such as splitting components and using memoization techniques.

To explore this issue further, the author conducted experiments using 5,000 radios in a React context. They built a small demo where selecting a radio updates its value in React state, which is then passed to child components as props. Initially, using React's documented pattern of memoizing components resulted in only the changed radios re-rendering. However, the performance difference was minimal when compared to using React's built-in `useSyncExternalStore` hook or the proposed `useContextSelector`.

The author then turned their attention to the React compiler, which automatically memoizes components and reuses expensive calculations when the selected value remains unchanged. After implementing a component with the compiler, the author observed that it matched the performance of the `useSyncExternalStore` approach. The compiler's ability to reuse memoized values and intermediate calculations meant that unchanged components did not incur additional re-renders.

In conclusion, the React compiler appears to address the need for context selectors without requiring additional workarounds. While the benchmark used in the article was narrow, the results suggest that leveraging the compiler could be a viable solution for optimizing React applications with context updates. The author emphasizes that while further exploration and refinement may be necessary, the compiler provides an effective, built-in alternative to creating custom context selectors.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at jjenzz.com →

More in Tech

Killedar: a fort guide that works where the signal dies

This is a submission for the Hacktoberfest Open-Source AI Challenge Week 1: Touch Grass What I Built Try it: killedar.onrender.com · Code: github.com/abhijeetkaze/killedar Halfway up Rajgad the bars…

  • Killedar is offline trek companion app for Maratha forts near Pune.
  • App uses PWA with Plan, Ask, and Listen screens for navigation.
  • Gemma language model powers Ask screen answers offline.

More from Sunday 11 October →