Tutorials

Learn ReactJS Components

Key Takeaways

  • React components are reusable UI building blocks that you compose into a component tree.
  • Use function components for new code. Class components remain supported, but aren't the recommended starting point.
  • Props are read-only inputs supplied by a parent; state is data a component remembers and updates.
  • The children prop lets a component wrap content supplied through nested JSX.

React components describe pieces of a user interface. A component can be a function or class that optionally receives inputs called props and returns a description of what to display. Start with function components, then combine them and pass props to build a page.

Create Your First React Function Component

Use these examples in an existing React project with JSX support, replacing its App component module one example at a time. JSX is the HTML-like syntax inside the JavaScript; these examples aren't standalone JavaScript you can paste into a browser console. For a project, follow the React quick start or React's build-tool setup guide.

export default function App() {
  return <div>Hello React!</div>;
}

This component doesn't need props. It simply returns JSX describing a greeting. The default export makes App available to the project's existing entry module.

Custom component names start with a capital letter: React treats <Header /> as a component reference and <header> as a built-in browser element. Function components return their UI directly; they don't need a render() method.

If the markup is unfamiliar, review the React JSX tutorial before continuing.

Pass Props to Child Components

A parent supplies props where it uses a child in JSX. The child receives one props object; destructuring, such as function Header({ name }), reads individual properties from that object. Props can contain strings, numbers, objects, arrays, or callback functions.

Compose App, Header, and Message

function Header({ name }) {
  return <h1>Welcome back, {name}</h1>;
}

function Message({ count }) {
  return (
    <div>
      <p>You have {count} new messages!</p>
    </div>
  );
}

export default function App() {
  return (
    <main>
      <Header name="Sam" />
      <Message count={5} />
    </main>
  );
}

App is the parent of Header and Message. Header receives the string "Sam"; Message receives the number 5. Quoted JSX attribute values are strings, while braces let you supply JavaScript expressions.

App
|-- Header   name="Sam"
`-- Message  count={5}

Props flow from parent to child.

This is component composition: building a larger UI from smaller components. Header and Message are child components, not a separate kind of component called a “sub-component.”

Reuse the Same Component With Different Inputs

To reuse Message, render it again with different props. Insert this fragment inside App's returned main element:

// Fragment: replace the existing Message element inside App.
<>
  <Message count={5} />
  <Message count={12} />
</>

Both uses share the same rendering logic but display different counts. A component is also useful when used only once if extracting it makes the page easier to understand.

Arrow Functions Work Too

An arrow function is another way to write a function component. This is an alternative Header definition, not an additional component to paste beside the original:

// Fragment: replace the earlier Header definition.
const Header = ({ name }) => (
  <h1>Welcome back, {name}</h1>
);

Choose the syntax your team finds readable. Neither syntax makes a component limited to displaying static content. Function components can use Hooks—React functions such as useState for remembering data and useEffect for synchronizing with external systems.

Compose React Components With children

Named props aren't the only way to supply content. JSX nested between a component's opening and closing tags becomes its children prop. A wrapper can render that content without knowing its specific structure.

function Card({ children }) {
  return <section className="card">{children}</section>;
}

export default function App() {
  return (
    <main>
      <Card>
        <h2>Inbox</h2>
        <p>You have 5 new messages!</p>
      </Card>
      <Card>
        <h2>Account</h2>
        <p>Your profile is up to date.</p>
      </Card>
    </main>
  );
}

Card owns the wrapper; App chooses the content. This separates a reusable container from the details displayed inside it. The same pattern works for panels, dialogs, and page layouts.

Understand Props Versus State

Props are supplied from outside a component. State is data a component remembers between renders. The useState Hook returns the current state value and a setter for requesting an update. A parent's state can become a child's prop when the parent passes it through JSX.

QuestionPropsState
Where does it come from?A parent supplies it.A component declares it, for example with useState.
How does it change?The parent supplies new inputs.The component requests an update through its setter.
Can you mutate it directly?No.No; use the setter and replace objects or arrays rather than mutating them.

Both props and state should be treated as read-only snapshots during rendering. For an interactive example, continue with React props versus state.

Recognize Class Components in Existing Code

React still supports class components, but recommends functions for new code. A class extends Component, defines a render method, and reads incoming props through this.props. You'll encounter this pattern in older applications and in custom error boundaries, which display fallback UI when descendant rendering fails.

import { Component } from 'react';

class Header extends Component {
  render() {
    return <h1>Welcome back, {this.props.name}</h1>;
  }
}

export default class App extends Component {
  render() {
    return (
      <main>
        <p>Hello React!</p>
        <Header name="Sam" />
      </main>
    );
  }
}

The parent-to-child data flow hasn't changed—only the component syntax has. You don't need classes merely because a component needs state or synchronization with an external system.

Understand Rendering and DOM Updates

Rendering means React calls components to calculate what the UI should look like. Common reasons a component renders include its initial appearance, a state update, its parent rendering, or a change to context it reads—shared data provided by an ancestor.

React reconciles the resulting component tree with the previous result, then commits the necessary changes to the browser's DOM. Running a component function doesn't necessarily mean changing the DOM.

Nor does every update render the entire application. React can skip work; for example, memo can skip a child's render when its props are unchanged. Memoization is a performance optimization, not a correctness guarantee—don't add it to every beginner example.

Common Mistakes

  • Defining components inside another component. Define Header and Message at module scope, outside App. A nested definition creates a new component type when the parent runs and can reset the child's state.
  • Changing inputs while rendering. Calculate JSX without mutating props, state, or existing external objects. Keep side effects out of rendering.
  • Confusing composition with definition nesting. Nest component usage in JSX, not component definitions inside JavaScript functions. Pass required data through props.

Practice With a Small Component Tree

Start with the App, Header, and Message example. Change the name, render Message twice with different counts, then wrap content in Card. Once that feels natural, build an interactive screen using the React form example with useState. Keep functions as your default and make each component's inputs easy to identify.

FAQ

What is a React component?

A React component is a function or class that describes part of a user interface. It can receive props, but doesn't have to use any. Function components are the recommended choice for new code.

How do you create a function component in React?

Define a JavaScript function with a capitalized name and return JSX describing its UI. Export it if another module needs to import it, then use it as a JSX element.

How do you pass props to a React component?

Supply named attributes at the JSX call site, such as <Header name="Sam" />. The child reads them from its props object, often using destructuring, and treats them as read-only.

What is the difference between props and state in React?

Props are inputs supplied by a parent; state is data a component remembers between renders. A function component can declare state with useState and request updates through the returned setter.

Are React class components still supported?

Yes. React supports class components, but recommends function components for new code. You may still encounter classes in existing applications and custom error-boundary implementations.

Further Reading

Written by Sam Erickson

Software engineer. I write every article on StackChief myself. Author of Mastering the Tech Interview. More about me