This is a companion repo to the blog post Repeat yourself a little less: Strategies for mitigating prop drilling with React and TypeScript. It demonstrates the problem of prop drilling in React+TypeScript, then shows several possible approaches for mitigating it.
Here's what the demo app looks like:
Here are the variations on the theme:
Technique | Demo | Lines | Notes |
---|---|---|---|
Initial Example | codepen | 64 | Starter app with two synchronized counters |
Fully Threaded | codepen | 99 | Going up to three counters illustrates the problem of prop drilling. |
Fewer Components | codepen | 46 | By inlining separate components, we dramatically reduce the amount of code. |
Single Object | codepen | 88 | Merging related props into a single object eliminates intermediate components' need to know the details of that object. |
Use Children | codepen | 72 | By passing children to a container component, we free it from having to understand its children's props. |
Context API | codepen | 91 | React's Context API provides a built-in way to do dependency injection. |
Pick Props | codepen | 93 | A TypeScript-friendly way to have one component "pick" props from another, both for types and at runtime. |
Do you have another way you like to deal with prop drilling? Send a PR to add it!
yarn
yarn type-check