React Composition is a development pattern based on React's original component model where we build components from other components using explicit defined props or the implicit children prop.
In terms of refactoring, React composition is a pattern that can be used to break a complex component down to smaller components, and then composing those smaller components to structure and complete your application.
Accordion Component
import React, { useState } from "react";
const Accordion = () => {
const [expanded, setExpanded] = useState(false);
const toggleExpanded = () => {
setExpanded((prevExpanded) => !prevExpanded);
};
return (
<div>
<button onClick={toggleExpanded}>
Header <span>{expanded ? "-" : "+"}</span>
</button>
{expanded && <div>Content</div>}
</div>
);
};
export default Accordion;
import React from "react";
import Accordion from "./components/Accordion";
const App = () => {
return <Accordion />;
};
export default App;
Editable Component
import React, { useState } from "react";
const Editable = () => {
const [editable, setEditable] = useState(false);
const [inputValue, setInputValue] = useState("Title");
const toggleEditable = () => {
setEditable((prevEditable) => !prevEditable);
};
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
return (
<div>
{editable ? (
<label htmlFor="title">
Title:
<input
type="text"
id="title"
value={inputValue}
onChange={handleInputChange}
/>
</label>
) : (
<>Title: {inputValue}</>
)}
<button onClick={toggleEditable}>{editable ? "Cancel" : "Edit"}</button>
</div>
);
};
export default Editable;
import React from "react";
import Editable from "./components/Editable";
const App = () => {
return <Editable />;
};
export default App;
Let's explore one similarity between these two components.
Problem: Notice how both the Accordion component and the Editable component share the same functionality, where both are dependent on a boolean and a function to update that boolean — in other words, a toggle functionality.
Solution: We can use a custom hook that will allow us to reuse this toggle logic in both components, and in any new component added in the future.
Top comments (0)