Components

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

Components

Components are the building blocks of any React application. They allow you to split the UI into independent, reusable pieces, and think about each piece in isolation.

What is a Component?

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

In modern React, components are written as JavaScript functions:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Component Composition

Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

Pure Components

React heavily encourages a functional programming concept called purity. A component is considered pure if:

  1. It minds its own business. It does not change any objects or variables that existed before it was called.
  2. Same inputs, same output. Given the same props, state, and context, it should always return the exact same JSX.

Strict Mode in React deliberately calls components twice in development to help surface impure behaviors.

Interview Questions

Q: What exactly defines a React component?
A: In modern React, a component is simply a JavaScript function that accepts an object of properties (props) and returns a React Element (JSX) that describes how a section of the UI should appear.

Q: Why must custom React components start with a capital letter?
A: The JSX parser requires it to distinguish custom components from native HTML elements. If you write <button>, React renders a native HTML button. If you write <Button>, React looks for a component function named Button in scope.