BP208: Keep components small and focused on a single responsibility

One of the best practices in React is to keep components small and focused on a single responsibility. This means that each component should have a clear and specific purpose, and should not try to do too much. By following this principle, you can make your code more modular, easier to understand, and more maintainable.

When a component tries to do too much, it can become difficult to understand and modify. It can also make it harder to reuse the component in other parts of your application. By breaking down your components into smaller, more focused pieces, you can make your code more flexible and easier to work with.

For example, if you have a component that displays a list of items, you might want to break it down into smaller components that handle specific tasks, such as rendering each item, handling user interactions, and managing the state of the component. This can make it easier to modify the behavior of the component, and can also make it easier to reuse the component in other parts of your application.

// Example of a component that does too much
function MyComponent(props) {
  const [items, setItems] = useState([]);

  function addItem(item) {
    setItems([...items, item]);
  }

  function removeItem(index) {
    const newItems = [...items];
    newItems.splice(index, 1);
    setItems(newItems);
  }

  return (
    <div>
      <h1>My Component</h1>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <button onClick={() => addItem('New Item')}>Add Item</button>
      <button onClick={() => removeItem(items.length - 1)}>Remove Last Item</button>
    </div>
  );
}

// Example of breaking down the component into smaller pieces
function MyComponent(props) {
  const [items, setItems] = useState([]);

  function addItem(item) {
    setItems([...items, item]);
  }

  function removeItem(index) {
    const newItems = [...items];
    newItems.splice(index, 1);
    setItems(newItems);
  }

  return (
    <div>
      <h1>My Component</h1>
      <ItemList items={items} removeItem={removeItem} />
      <AddItemButton addItem={addItem} />
    </div>
  );
}

function ItemList(props) {
  return (
    <ul>
      {props.items.map((item, index) => (
        <Item key={index} item={item} index={index} removeItem={props.removeItem} />
      ))}
    </ul>
  );
}

function Item(props) {
  return (
    <li>
      {props.item}
      <button onClick={() => props.removeItem(props.index)}>Remove</button>
    </li>
  );
}

function AddItemButton(props) {
  return (
    <button onClick={() => props.addItem('New Item')}>Add Item</button>
  );
}

Comments

No Comments Yet.
Be the first to tell us what you think.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play