DEV Community

Cover image for ReactJS Design Pattern ~Children Pattern~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Design Pattern ~Children Pattern~

・Children pattern allows us to pass components as children through the children prop instead of rendering them directly. This pattern prevents unnecessary re-renders because the parent component doesn't own the child components' state, and it provides flexibility by allowing any compoent to be passed as a slot.

import { useState } from "react";

function Wrapper({children, showContent}) {
  return (
    <div>
      {showContent ? <p>{children}</p> : null} 
    </div>
  )
}

function App() {
  const [showContent, setShowContent] = useState(true);

  const content = "This is the content";

  return (
    <div>
      <h1>Children Pattern</h1>
      <button onClick={() => setShowContent(!showContent)}>
        Toggle Content
      </button>
      <Wrapper showContent={showContent}>
      {content}
      </Wrapper>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)