ReactJS Design Pattern ~Colocating State~
Source: Dev.to
Collocating State Overview
Collocating State is placing a state as close as possible to where it’s used. This pattern reduces complexity and makes components easier to understand.
Before
App component
function App() {
const [isVisible, setIsVisible] = useState(false);
return (
);
}
ToggleSection component
function ToggleSection({ isVisible, setIsVisible }) {
return (
setIsVisible(!isVisible)}>
{isVisible ? "Hide" : "Show"} Content
{isVisible && (
This content can be toggled!
)}
);
}
After
App component (state removed)
function App() {
// Removed the isVisible state.
return (
);
}
ToggleSection component (state colocated)
function ToggleSection() {
// Placed the isVisible state here.
const [isVisible, setIsVisible] = useState(false);
return (
setIsVisible(!isVisible)}>
{isVisible ? "Hide" : "Show"} Content
{isVisible && (
This content can be toggled!
)}
);
}