Ben Ilegbodu 🏀👨🏾‍💻 Profile picture
#Christ follower, husband, father of 3️⃣. Tweetin' on #React #TypeScript #DivOps @NBA. 🌍 Speaker @GoogleDevExpert @MVPAward. Principal FE Eng @stitchfix

Jun 1, 2021, 8 tweets

React component patterns help us create reusable and extendable components that provide some inversion of control to their parent

Here's a thread of 5️⃣ such patterns

But first let's start with a vanilla <Button> component with "normal" props & how it's used

/thread 🧵👇🏾

1️⃣ Placeholder props

The placeholder props pattern allows the shared component to control its layout & any logic, but give some control to the parent for the display

For our Button comp, the `startIcon` & `endIcon` props can be <svg>, <img> or even other React components

🧵👇🏾

2️⃣ Polymorphic components

The polymorphic component pattern comes in handy when we need flexibility on the rendered element

For semantic HTML or a11y reasons we may need to change the root element. We can even pass another component for the `as` prop (react-router <Link>)

🧵👇🏾

3️⃣ Controlled components

The controlled components pattern gives parents flexible control over the shared component's UI logic. The passed in props can make it "controlled" or "uncontrolled"

(see blog post below for more details)

🧵👇🏾

4️⃣ Render props

The render prop pattern comes in handy when a shared component needs to control layout of any common UI and stateful logic, but the visual look-and-feel is left to the parent component

Render props are typically named `render` or use the `children` prop

🧵👇🏾

5️⃣ Compound components

When we require full customization of multiple interconnected components, the compound components pattern is very helpful

However it's more complex to implement. IMO it makes the complex use case easier but makes the simple use case more complex

🧵👇🏾

I can only explain so much in 280 characters, so if you wanna learn more I suggest you check out the blog post with all the explanations

What other React component patterns do you use often? 🤔

🧵👇🏾

benmvp.com/blog/picking-r…

If you're a fan of a no-frills newsletter, might I suggest the BenMVP Newsletter?

You'll get a weekly frontend-focused email covering JS/TS, React & more!

Keep learning my friends. 🤓

benmvp.com/subscribe/?utm…

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling