Reduce Prop Drilling in React with Composition

𝐒𝐭𝐨𝐩 𝐏𝐫𝐨𝐩 𝐃𝐫𝐢𝐥𝐥𝐢𝐧𝐠! You have a user object at the top of your app, and you end up passing it through 5 different components—Layout, Page, Header, Sidebar—just so a tiny <Avatar /> at the very bottom can use it. By the time you're done, your middle components are "polluted" with props they don't even care about. It makes refactoring a nightmare and testing a chore. Before you reach for a heavy state management library like Redux or Zustand, try a simpler built-in pattern: 𝘊𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵 𝘊𝘰𝘮𝘱𝘰𝘴𝘪𝘵𝘪𝘰𝘯. 𝐓𝐡𝐞 "𝐏𝐫𝐨𝐩 𝐃𝐫𝐢𝐥𝐥𝐢𝐧𝐠": <𝐀𝐩𝐩> → <𝐋𝐚𝐲𝐨𝐮𝐭 𝐮𝐬𝐞𝐫={𝐮𝐬𝐞𝐫}> → <𝐇𝐞𝐚𝐝𝐞𝐫 𝐮𝐬𝐞𝐫={𝐮𝐬𝐞𝐫}> → <𝐀𝐯𝐚𝐭𝐚𝐫 𝐮𝐬𝐞𝐫={𝐮𝐬𝐞𝐫} /> 𝐓𝐡𝐞 "𝐂𝐨𝐦𝐩𝐨𝐬𝐢𝐭𝐢𝐨𝐧" 𝐅𝐢𝐱: 𝐏𝐚𝐬𝐬 𝐭𝐡𝐞 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭 𝐢𝐭𝐬𝐞𝐥𝐟 𝐚𝐬 𝐚 𝐩𝐫𝐨𝐩 𝐨𝐫 𝐮𝐬𝐞 {𝐜𝐡𝐢𝐥𝐝𝐫𝐞𝐧}. Instead of passing data down, you "lift" the child component up. This means your Header doesn't even need to know the user exists—it just renders whatever you put inside it. Why I've started leaning into this: 𝐂𝐥𝐞𝐚𝐧𝐞𝐫 𝐂𝐨𝐝𝐞: No more "pass-through" props clogging up your components. 𝐓𝐫𝐮𝐞 𝐑𝐞𝐮𝐬𝐚𝐛𝐢𝐥𝐢𝐭𝐲: Your Header is now truly generic. 𝐄𝐚𝐬𝐢𝐞𝐫 𝐓𝐞𝐬𝐭𝐢𝐧𝐠: You can test each piece in total isolation. React isn't just about building components; it's about how you compose them. Keep your components "dumb" and your architecture smart. I'm curious—how many layers of prop drilling do you hit before you force a refactor?  #ReactJS #WebDevelopment #SoftwareEngineering #CleanCode #JavaScript #FrontEnd

  • graphical user interface, text

I don’t use react a lot but rather vue , where I would just use provide/inject pattern. I think the equivalent here is context api in react no?

Like
Reply

To view or add a comment, sign in

Explore content categories