DEV Community

Cover image for ReactJS Design Pattern ~Colocating State~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Design Pattern ~Colocating State~

・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

function App() {
  const [isVisible, setIsVisible] = useState(false);
  return (
    <div>
      <h1>Colocating State Example</h1>
      <ToggleSection isVisible={isVisible} setIsVisible={setIsVisible}/>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
function ToggleSection({isVisible, setIsVisible}) {
  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? "Hide" : "Show"} Content
      </button>
      {isVisible && (
        <div>
          <p>This content can be toggled!</p>
        </div>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

After

function App() {
//Removed the isVisible state.
  return (
    <div>
      <h1>Colocating State Example</h1>
      <ToggleSection />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
function ToggleSection() {
//Placed the isVisible state here.
   const [isVisible, setIsVisible] = useState(false);
  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? "Hide" : "Show"} Content
      </button>
      {isVisible && (
        <div>
          <p>This content can be toggled!</p>
        </div>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)