Compound Components
Compound Components in React are patterns where the parent component shares its implicit State and logic with the child component using the Context API. Here the Child component depends on the state and logic provided by the parent component. Compound Component allows the child component to communicate with the parent component which leads to a more cleaner API’s. The child component doesn’t need to worry much about the data because it can directly get it from the parent component.
Example: Now, let us understand Compound Components through an example.
Javascript
// App.js import React, { createContext, useState, useContext } from 'react' ; const NewComponent = createContext(); function ParentComponent({ children }) { const [variable, setVar] = useState( "I'm a Parent Component" ); return ( <NewComponent.Provider value={{ variable, setVar }}> {children} </NewComponent.Provider> ); } function ChildComponent() { const { variable } = useContext(NewComponent); return <h1>{variable}</h1>; } function App() { return ( <ParentComponent> <ChildComponent /> </ParentComponent> ); } export default App |
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?