Tuesday, May 13, 2025

BIS601 FSD - Why should we Compose Components as much as possible?

 

Why Compose Components?

Instead of writing everything in one file or component, you break down UI into logical, small components and compose them together like building blocks.

We’ll build:

  • A Greeting component

  • A Counter component

  • Compose both in a parent App component

Greeting.jsx

import React from 'react';


function Greeting(props) {

  return <h2>Hello, {props.name}!</h2>;

}


export default Greeting;


Counter.jsx

import React, { useState } from 'react';


function Counter() {

  const [count, setCount] = useState(0);


  return (

    <div>

      <p>Count: {count}</p>

      <button onClick={() => setCount(count + 1)}>Increment</button>

    </div>

  );

}


export default Counter;


App.jsx

import React from 'react';

import Greeting from './Greeting';

import Counter from './Counter';


function App() {

  return (

    <div style={{ textAlign: 'center', marginTop: '2rem' }}>

      <h1>Component Composition Example</h1>

      <Greeting name="Student" />

      <Counter />

    </div>

  );

}


export default App;


Summary

  • Each component does one thing well

  • App composes them to form the full UI

  • Props (like name) help in customizing reused components

No comments:

Post a Comment