|
| 1 | +# 2. Replace recursive prop passing with React Context in TreeView components |
| 2 | + |
| 3 | +Date: 2025-07-22 |
| 4 | + |
| 5 | +## Status |
| 6 | + |
| 7 | +Accepted |
| 8 | + |
| 9 | +## Context |
| 10 | + |
| 11 | +The TreeView and TreeNode components share props that need to be passed from |
| 12 | +parent to child. Previously, we implemented a recursive function that would |
| 13 | +traverse the component tree to locate TreeNode instances (including those |
| 14 | +wrapped in other components) and pass props down to them. |
| 15 | + |
| 16 | +This approach had several significant drawbacks: |
| 17 | + |
| 18 | +- The recursive traversal was computationally expensive and energy-intensive |
| 19 | +- Props were not always passed down correctly to wrapped TreeNode components |
| 20 | +- Users could not reliably use TreeNode components inside custom wrapper classes |
| 21 | +- The implementation was brittle and difficult to maintain |
| 22 | + |
| 23 | +One specific issue that highlighted this problem: |
| 24 | +https://github.com/carbon-design-system/carbon/issues/19522 |
| 25 | + |
| 26 | +## Decision |
| 27 | + |
| 28 | +We will replace the recursive prop passing mechanism with React's Context API. |
| 29 | +This allows direct communication between TreeView (parent) and TreeNode (child) |
| 30 | +components through the React context system, eliminating the need to traverse |
| 31 | +and analyze the component tree structure. |
| 32 | + |
| 33 | +The implementation was completed in: |
| 34 | +https://github.com/carbon-design-system/carbon/pull/19626 |
| 35 | + |
| 36 | +## Consequences |
| 37 | + |
| 38 | +Users can now wrap TreeNode components with any number of custom wrapper |
| 39 | +components without affecting the parent-child communication. This provides much |
| 40 | +greater flexibility in component composition while improving performance by |
| 41 | +eliminating the recursive tree traversal. The solution is also more maintainable |
| 42 | +and follows React best practices for component communication. |
0 commit comments