DEV Community

Zamora
Zamora

Posted on

Senior level: Core Concepts of React

Components

What Are Components?

Components are the fundamental units of a React application. They enable the building of complex UIs from small, isolated pieces of code. Each component encapsulates its own structure, logic, and styling, making it reusable and maintainable. Components can be compared to the microservices architecture in backend development, where each service/component handles a specific part of the application, promoting separation of concerns and reusability.

Components can be divided into two main categories:

  • Presentational Components: Focus solely on how things look. They receive data and callbacks exclusively via props.
  • Container Components: Focus on how things work. They fetch data, perform logic, and pass down props to presentational components.

Functional vs. Class Components

Functional Components

Functional components are simple JavaScript functions that accept props and return React elements. With the introduction of Hooks in React 16.8, functional components have become powerful enough to handle state and lifecycle events, reducing the need for class components.

Example of a Functional Component:

import React from 'react';

const Greeting = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

export default Greeting;
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Simpler and more concise syntax.
  • Easier to test and debug.
  • Hooks provide a flexible way to handle state and side effects.

Class Components

Class components extend React.Component and must implement a render() method to return React elements. They were the standard for handling state and lifecycle methods before Hooks were introduced.

Example of a Class Component:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

export default Greeting;
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Useful for understanding legacy code.
  • Provide lifecycle methods directly on the component class.

Creating and Using Components

To create a component, define a function or class that returns a React element. Use components within other components to build complex UIs.

Example of Creating and Using a Functional Component:

import React from 'react';

// Define the Greeting component
const Greeting = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

// Define the App component
const App = () => {
  return (
    <div>
      <Greeting name="Alice" />
      <Greeting name="Bob" />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, the Greeting component is used within the App component. The name prop is passed to Greeting and displayed inside the <h1> tag.

JSX (JavaScript XML)

Introduction to JSX

JSX stands for JavaScript XML. It is a syntax extension for JavaScript that looks similar to HTML. JSX is used with React to describe what the UI should look like. It makes the code easier to write and understand by providing a more familiar syntax for defining the structure of your components.

JSX is syntactic sugar for React.createElement(component, props, ...children).

Example of JSX:

const element = <h1>Hello, world!</h1>;
Enter fullscreen mode Exit fullscreen mode

This JSX code gets compiled to:

const element = React.createElement('h1', null, 'Hello, world!');
Enter fullscreen mode Exit fullscreen mode

Embedding Expressions in JSX

JSX allows embedding JavaScript expressions within curly braces {}. This feature enables dynamic rendering of content and makes the JSX powerful and flexible.

Example of Embedding Expressions in JSX:

const name = 'Alice';
const element = <h1>Hello, {name}!</h1>;

const getGreeting = (name) => `Hello, ${name}!`;
const greetingElement = <h1>{getGreeting('Bob')}</h1>;
Enter fullscreen mode Exit fullscreen mode

In these examples, expressions inside {} are evaluated, and their results are embedded in the JSX.

JSX vs. HTML

While JSX looks similar to HTML, there are several important differences:

  1. JSX Attributes: Attributes in JSX use camelCase instead of lowercase. For instance, class becomes className, and onclick becomes onClick.
   <div className="container"></div>
   <button onClick={handleClick}>Click Me</button>
Enter fullscreen mode Exit fullscreen mode
  1. JavaScript Expressions: You can embed JavaScript expressions inside JSX using curly braces {}, which is not possible in plain HTML.
   const isLoggedIn = true;
   <div>{isLoggedIn ? 'Welcome back!' : 'Please log in.'}</div>
Enter fullscreen mode Exit fullscreen mode
  1. Self-Closing Tags: JSX requires self-closing tags for elements without children, similar to XML.
   <img src="image.jpg" />
Enter fullscreen mode Exit fullscreen mode
  1. Fragments: JSX supports fragments to group multiple elements without adding extra nodes to the DOM.
   <>
     <h1>Title</h1>
     <p>Description</p>
   </>
Enter fullscreen mode Exit fullscreen mode
  1. Event Handling: In JSX, event handlers are camelCase and passed as functions, unlike HTML where they are strings.
   <button onClick={handleClick}>Click Me</button>
Enter fullscreen mode Exit fullscreen mode
  1. Conditionals and Loops: Unlike HTML, you can use JavaScript conditionals and loops directly in JSX.
   const items = ['Apple', 'Banana', 'Cherry'];
   return (
     <ul>
       {items.map(item => <li key={item}>{item}</li>)}
     </ul>
   );
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding components and JSX is crucial for mastering React. Components allow you to break down your UI into reusable, independent pieces, while JSX provides a syntax that closely resembles HTML, making it easier to describe your UI. As a senior developer, deepening your knowledge of these core concepts enables you to build more efficient, maintainable, and scalable React applications. Leveraging these principles, you can architect complex applications, mentor junior developers, and contribute to the overall success of your projects.

Top comments (0)