Know your React Basics

Dev Balaji
5 min readOct 24, 2023

--

React is an open-source JavaScript library used for building user interfaces (UIs) in web applications. It was developed and is maintained by Facebook and a community of individual developers and companies. React is particularly popular for creating interactive, dynamic, and high-performance web applications.

Here’s a detailed explanation of React, its architecture, and examples:

Why React?

  1. Declarative UI: React allows you to describe the UI as a set of components, and it automatically updates and renders the components when the underlying data changes. This declarative approach simplifies UI development, making it more predictable and maintainable.
  2. Component-Based: React is based on the concept of components. You build your UI by creating reusable components that can be composed to form complex interfaces. This makes it easy to manage and scale applications.
  3. Virtual DOM: React uses a Virtual DOM to efficiently update the actual DOM. Instead of making direct changes to the real DOM, React calculates the minimal changes required to update the UI and then applies those changes. This leads to better performance.
  4. Unidirectional Data Flow: React enforces a one-way data flow, which makes it easier to understand how data is passed and modified within your application. This unidirectional flow ensures that the child components cannot directly modify the parent’s state.

React Architecture

React’s architecture consists of several key concepts:

  1. Components: The building blocks of a React application. Components can be functional (stateless) or class-based (stateful) and are responsible for rendering parts of the UI. Components can be classified into two main types:

Functional Components: These are stateless components that are defined as JavaScript functions. They take in props (properties) as input and return what should be rendered. For example, a simple React component that displays a “Hello, World!” message:

function HelloWorld() {
return <div>Hello, World!</div>;
}

Class Components: These are stateful components defined as ES6 classes. They have a render method for defining what should be rendered and can maintain their own internal state.

class MyClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

render() {
return <div>{this.state.count}</div>;
}
}

2. Virtual DOM: React maintains a virtual representation of the actual DOM. When the state of a component changes, React compares the new virtual DOM with the previous one to determine the minimum set of changes needed to update the real DOM efficiently.

3. State and Props: React components can have both state and props. The state represents mutable data managed by a component, while props are immutable properties passed from a parent component.

Props (Properties):

Props are a way to pass data from parent to child components. They are read-only and help in creating reusable and composable components. You can pass any data type as props, including functions, objects, or even other React components.

For example, in a parent component:

<ChildComponent text="Hello, World!" />

In the child component, text is accessible as props.text.

State:

State is an object that represents the data a component needs to keep track of during its lifecycle. It is mutable and can be updated using the this.setState() method. When the state changes, React will re-render the component to reflect the updated data.

State is typically used for managing data that can change within a component, like form inputs or counters. In class components, you initialize state in the constructor.

class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
}

4. Lifecycle Methods: React components have various lifecycle methods that allow developers to hook into component creation, updates, and destruction. These methods are useful for performing actions at specific points in the component’s lifecycle.

These methods include:

  • componentDidMount: Called after a component is rendered for the first time. Useful for data fetching and setup.
class MyComponent extends React.Component {
componentDidMount() {
// This method is called after the component is added to the DOM.
}
}
  • componentDidUpdate(prevProps, prevState): Called after a component update, e.g., after a state change.
class RealTimeChart extends React.Component {
componentDidUpdate(prevProps, prevState) {
if (this.props.data !== prevProps.data) {
// Update the chart when new data is received.
this.updateChart();
}
}
}
  • componentWillUnmount: Called before a component is removed from the DOM. Useful for cleanup.
class RealTimeComponent extends React.Component {
componentWillUnmount() {
// Unsubscribe from data streams or close connections.
}
}

These lifecycle methods are integral to real-time applications, where data changes frequently, and responsiveness and performance are critical. By using these methods effectively, you can manage data subscriptions, update the UI efficiently, and ensure proper cleanup when components are no longer needed. This is particularly important in scenarios like real-time chat applications, real-time dashboards, live sports scores, and more, where timely data updates are a core feature.

5. Virtual DOM: React’s Virtual DOM is a lightweight in-memory representation of the actual DOM. When the state of a component changes, React doesn’t immediately update the real DOM. Instead, it calculates the difference between the previous virtual DOM and the new one. This process is called “reconciliation.”

The Virtual DOM allows React to minimize the number of updates to the real DOM, making the application more efficient and improving performance.

6. Unidirectional Data Flow: React enforces a one-way data flow. Data is passed from parent components to child components through props. Child components can’t directly modify the state of their parents. Instead, if a child needs to change something, it can do so through callbacks (functions) passed as props.

7. Reconciliation: Reconciliation is the process of updating the actual DOM based on the changes detected in the Virtual DOM. React’s diffing algorithm determines the minimum set of changes required to update the DOM efficiently.

8. Keyed Elements: When rendering lists of elements in React, it’s important to assign a unique key prop to each item. This helps React efficiently update the list by recognizing which items have been added, removed, or reordered.

const items = [1, 2, 3];

<ul>
{items.map(item => (
<li key={item}>{item}</li>
))}
</ul>

React Example

Let’s create a simple React example to illustrate the concepts:

import React, { Component } from 'react';

class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

incrementCount = () => {
this.setState({ count: this.state.count + 1 });
}

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}

export default Counter;

In this example, we have a Counter component with state, a method to update the state, and a button that triggers the state update when clicked. React takes care of efficiently updating the DOM when the count state changes.

This is just a basic overview of React, its architecture, and a simple example. React can be used in combination with other libraries and tools to build complex web applications. Its modular and component-based structure, along with its efficient rendering using the Virtual DOM, makes it a popular choice for frontend development.

--

--

Dev Balaji

🚀 Tech Enthusiast | 🌟 Mastering JavaScript & Frameworks | 💡 Sharing Tips & Tricks | 📘 Aspiring Blogger & Architect | 🐍 Python Practitioner