Separation of concerns means keeping different parts of your code focused on one job. This makes your app easier to understand and fix.
0
0
Separation of concerns in React
Introduction
When building a React app with multiple features like buttons, lists, and forms.
When you want to make your code easier to test and change later.
When working with a team so everyone can work on different parts without confusion.
When you want to reuse parts of your app in other projects.
When you want to keep your UI, data, and logic separate for clarity.
Syntax
React
function ComponentA() { // Handles UI only return <div>UI here</div>; } function ComponentB() { // Handles data or logic const data = fetchData(); return <ComponentA data={data} />; }
Each component should have one clear job, like showing UI or handling data.
Use props to pass data between components to keep them separate.
Examples
This Button component only shows a button and calls a function when clicked. It does not handle what happens on click.
React
function Button({ onClick, label }) { return <button onClick={onClick}>{label}</button>; }
The App component handles the logic for what happens when the button is clicked. It passes this to Button as a prop.
React
function App() { const handleClick = () => alert('Clicked!'); return <Button onClick={handleClick} label="Click me" />; }
Sample Program
This Counter app splits the UI and logic into separate parts. CounterDisplay only shows the count. CounterButtons only shows buttons and calls functions when clicked. The main Counter component holds the count state and logic to change it.
This makes the code clear and easy to change or reuse parts.
React
import React, { useState } from 'react'; function CounterDisplay({ count }) { return <h1>Count: {count}</h1>; } function CounterButtons({ onIncrement, onDecrement }) { return ( <div> <button onClick={onIncrement} aria-label="Increase count">+</button> <button onClick={onDecrement} aria-label="Decrease count">-</button> </div> ); } export default function Counter() { const [count, setCount] = useState(0); const increment = () => setCount(c => c + 1); const decrement = () => setCount(c => c - 1); return ( <main> <CounterDisplay count={count} /> <CounterButtons onIncrement={increment} onDecrement={decrement} /> </main> ); }
OutputSuccess
Important Notes
Keep components small and focused on one job.
Use props to share data and actions between components.
Separation helps with testing, reusing, and fixing code.
Summary
Separation of concerns means each part of your app does one clear thing.
Use small components for UI and separate logic or data handling.
This makes your React app easier to read, test, and maintain.