Context API and Composition
The Context API in React allows sharing state and logic across components without manually passing props through each level of the component tree. It provides global access to data via a Context, enabling nested and child components to access required data easily. By composing components within a Context component created using createContext()
, data can be accessed using useContext()
without needing props. This approach simplifies component composition and is particularly useful for sharing common state and logic throughout a component tree hierarchy.
Example: This example demostrates the implementation of Context API.
Javascript
// App.js import React, { createContext } from "react" ; import ParentComponent from "./ParentComponent" ; export const NewContext = createContext(); const text = { parent: "I'm from parent Component" , child: "I'm from child Component" }; function App() { return ( <NewContext.Provider value={text}> <ParentComponent /> </NewContext.Provider> ); } export default App; |
Javascript
// ParentComponent.js import React, { useContext } from "react" ; import { NewContext } from "./App" ; import ChildComponent from "./ChildComponent" ; function ParentComponent() { const data = useContext(NewContext); return ( <div> <h1> {data.parent} </h1> <ChildComponent /> </div> ); }; export default ParentComponent; |
Javascript
// Childcomponent.js import React, { useContext } from "react" ; import { NewContext } from "./App" ; function ChildComponent() { const data = useContext(NewContext); return ( <h1> {data.child} </h1> ); } export default ChildComponent; |
Output :
React JS Component Composition
Component composition in React involves the inclusion of one or more components in a single component, where each sub-component can further consist of additional components. Components in React are building blocks that are used to create user interfaces (UIs).
Table of Content
- What is a Component Composition in React?
- How can composition help performance?
- Composing Components with props
- Higher order components
- Render Props pattern
- Using Hooks in Component Composition
- Context API and Composition
- Compound Components
- Component Composition Patterns
- Containment Pattern
- Specialization Pattern
- Why Composition Wins Over Inheritance?
Contact Us