DEV Community

Cover image for ReactJS Hook Pattern ~Effect Separation Pattern~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Hook Pattern ~Effect Separation Pattern~

This pattern means separating concerns in a single effect into multiple useEffect. This makes codebases maintainable, allowing each effect to have its own dependency array.

import { useState, useEffect } from "react";

function App() {
  const [name, setName] = useState("John");
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Name: ${name}`;
  }, [name]);

  useEffect(() => {
    console.log(`Count: ${count}`);
  }, [count]);

  return (
    <div>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter your name"
      />

      <button onClick={() => setCount(count + 1)}>Count: {count}</button>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)