React Composition - A Viable Alternative to React Context (2024)

Ever since React 16.8 introduced us to React hooks, many developers started leveraging React context as a trim solution to the tedious task of "prop drilling".

What is "Prop Drilling"?

React's design revolves around building UI components, which, when bundled together, form a component tree hierarchy. For a deep nested component to access data from higher up, the data must be cascaded downwards as props, the building blocks of React components. Efforts to evade prop drilling are mainly aimed at reducing redundant component re-renders. When a higher-level component modifies its data and disseminates it using props, all intervening components get triggered to re-render.

React Composition - A Viable Alternative to React Context (1)

(image sourced from the React documentation)


How does React Context help?

React Context offers an excellent solution to prop drilling. It enables smooth transportation of data directly to the components that need it, bypassing intermediary children components.

React Composition - A Viable Alternative to React Context (2)

Essentially, Context represents React's interpretation of dependency injection.

Sample Code Illustration:

1const ThemeContext = React.createContext();23function ThemeProvider(props) {4 const [theme, setTheme] = React.useState("dark");5 const value = [theme, setTheme];6 return <ThemeContext.Provider value={value} {...props} />;7}89function ThemeDisplay() {10 const [theme] = React.useContext(ThemeContext);11 return <div>{`The current theme is ${theme}`}</div>;12}1314function Theme() {15 const [, setTheme] = React.useContext(ThemeContext);16 const changeTheme = () => setTheme("light");17 return <button onClick={changeTheme}>Change theme to light</button>;18}1920function App() {21 return (22 <div>23 <ThemeProvider>24 <ThemeDisplay />25 <Theme />26 </ThemeProvider>27 </div>28 );29}30

The Contention Surrounding Context Usage

Although the use of React Context is becoming more common, even the official React documentation advises against its overuse.

// ... rest of the code remains unchanged

Embracing React Composition

An alternative strategy worth considering is using JSX as children, leveraging the power of composition to achieve results similar to the Context API.

While this strategy doesn't directly tackle the issue of re-rendering all child components, it offers significant benefits in terms of component reuse. For example, the Dashboard Content component, which doesn't require user data, can be reused elsewhere for a different Dashboard without needing a context provider, thereby avoiding implicit dependencies.

Sample Implementation:

1export default function App() {2 const [user, setUser] = React.useState(null);34 return (5 <div>6 {user ? (7 <LoggedinWrapper>8 <Homepage>9 <LogoutButton onLogout={() => setUser(null)} />10 <Navigation />11 <HomepageContent>12 <Profile user={user} />13 </HomepageContent>14 </Homepage>15 </LoggedinWrapper>16 ) : (17 <SigninPage onLogin={() => setUser({ name: 'Bob' })} />18 )}19 </div>20 );21}2223function LogoutButton({ onLogout }) {24 return <button onClick={onLogout}>Logout</button>;25}2627function LoggedinWrapper({ children }) {28 return (29 <React.Fragment>30 <h1>You are signed in!</h1>31 {children}32 </React.Fragment>33 );34}3536function Navigation() {37 return (38 <React.Fragment>39 <h2>Dashboard Nav</h2>40 </React.Fragment>41 );42}4344function Homepage({ children }) {45 return (46 <React.Fragment>47 <h3>Dashboard</h3>48 {children}49 </React.Fragment>50 );51}5253function HomepageContent({ children }) {54 return (55 <React.Fragment>56 <h3>Homepage</h3>57 {children}58 </React.Fragment>59 );60}6162function Profile({ user }) {63 return (64 <ul>65 <li>Username: {user.name} </li>66 </ul>67 );68}6970function SigninPage({ onLogin }) {71 return (72 <React.Fragment>73 <h1>Sign In</h1>74 <button onClick={onLogin}>Login</button>75 </React.Fragment>76 );77}78

In contrast, the mandatory need for a context provider can be challenging when trying to render a component outside its allotted provider. Often, developers encapsulate the entire application within a global context provider, which could lead to performance issues, as previously mentioned.

In a nutshell, composition can serve as a feasible alternative to relying on React context to prevent prop drilling.

References

React Composition - A Viable Alternative to React Context (2024)
Top Articles
The thought experiment: What would happen if everyone on the planet suddenly went vegan?
DOS Command: XCOPY
Netr Aerial Viewer
Worcester Weather Underground
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Combat level
Online Reading Resources for Students & Teachers | Raz-Kids
Toyota Campers For Sale Craigslist
Autobell Car Wash Hickory Reviews
A Fashion Lover's Guide To Copenhagen
FIX: Spacebar, Enter, or Backspace Not Working
Oriellys St James Mn
Erin Kate Dolan Twitter
Oxford House Peoria Il
Immediate Action Pathfinder
Best Fare Finder Avanti
Wisconsin Women's Volleyball Team Leaked Pictures
Google Feud Unblocked 6969
Download Center | Habasit
"Une héroïne" : les funérailles de Rebecca Cheptegei, athlète olympique immolée par son compagnon | TF1 INFO
Free Online Games on CrazyGames | Play Now!
Christina Steele And Nathaniel Hadley Novel
Jeff Now Phone Number
1973 Coupe Comparo: HQ GTS 350 + XA Falcon GT + VH Charger E55 + Leyland Force 7V
Bellin Patient Portal
Troy Gamefarm Prices
Spiritual Meaning Of Snake Tattoo: Healing And Rebirth!
4 Times Rihanna Showed Solidarity for Social Movements Around the World
Tuw Academic Calendar
Snohomish Hairmasters
Grave Digger Wynncraft
Delete Verizon Cloud
Infinite Campus Asd20
Orange Park Dog Racing Results
1475 Akron Way Forney Tx 75126
Gina's Pizza Port Charlotte Fl
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Santa Cruz California Craigslist
Gold Nugget at the Golden Nugget
Babylon 2022 Showtimes Near Cinemark Downey And Xd
Studio 22 Nashville Review
Eastern New Mexico News Obituaries
Booknet.com Contract Marriage 2
Royals Yankees Score
Race Deepwoken
Theater X Orange Heights Florida
Meee Ruh
Is Chanel West Coast Pregnant Due Date
Grand Park Baseball Tournaments
BYU Football: Instant Observations From Blowout Win At Wyoming
O'reilly's Eastman Georgia
La Fitness Oxford Valley Class Schedule
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 6244

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.