Motivating Contexts in React
- Context is used for passing data through the component tree without passing props down manually
- In React applications, data is passed parent-to-child via props
-
However, this can become cumbersome for certain props:
- Locale preferences
- UI themese
- These props are required by many components within an application
Use Cases for Context
- Context is used for sharing data that may be considered as global for a tree of React components
-
The following are a few examples:
- Authenticated user
- Theme
- Preferred language
- etc.
- Essentially, context is used when data needs to be accessed by many components at different nesting levels
- It should be used sparingly, since reusing components becomes difficult
- If we're only interested in avoiding passing props through many levels, then component composition is often a simpler
References
Previous
Next