Skip to main content

Command Palette

Search for a command to run...

Understand ReactJS - Part 1 ☘️☘️☘️

Updated
5 min readView as Markdown
Understand ReactJS - Part 1 ☘️☘️☘️
K

I am a developer who is highly interested in TypeScript. My tech stack has been full-stack TS such as Angular, React with TypeScript and NodeJS.

React JS Virtual DOM Explained - Part 2 🌲🌲🌲
Advance React Hooks - Part 3💯💯💯
React Context Guide - Part 4 🔔🔔🔔
ReactJS Explained Hooks - Part 5 ⚡️⚡️⚡️

ReactJS Explained Hooks - ParReact PureComponent: A Deep Dive - part 6 ❤️‍🔥❤️‍🔥❤️‍🔥

Part 1: Introduction to ReactJS and Lifecycle

💥💥💥 React.js is a JavaScript library used primarily for building dynamic user interfaces, especially for single-page applications (SPAs). Its component-based architecture allows you to create reusable UI elements, making development efficient and organized. Here’s a breakdown of its core concepts and strengths:

Key Concepts in React.js:

Components:

  • Functional Components: The modern standard for React components. They are simpler, easier to test, and often faster because they lack the overhead of a class.

  • Class Components: An older way of defining components, still supported but less common with the rise of hooks.

  • Components are the basic building blocks in React, and each one represents part of the user interface.

  • State:

    • State is an object that holds dynamic data that may change over time, driving reactivity in React components.

    • In functional components, useState is a React hook that allows you to manage local state.

  • Props:

    • Props (short for “properties”) are used to pass data from one component to another, making components more reusable and customizable.

    • Props are immutable, so they cannot be changed within the receiving component.

  • Hooks:

    • React Hooks, introduced in version 16.8, allow functional components to manage state and lifecycle methods.

    • Common hooks include useState (for state management), useEffect (for side effects like API calls), useContext (for context API), useRef (for referencing DOM nodes or holding mutable values), and useReducer (for complex state logic).

  • Context API:

    • The Context API provides a way to share data like themes, language, or user info across components without passing props down through each level manually.

    • It can be combined with useContext for easier access in functional components.

  • Lifecycle Methods:

    • In class components, lifecycle methods manage what happens at different stages (e.g., componentDidMount, componentDidUpdate).

    • In functional components, useEffect serves a similar purpose.

  • JSX (JavaScript XML):

    • JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript, making it easier to visualize component structure.
  • Advantages of Using React:

  • Virtual DOM: React’s Virtual DOM optimizes UI updates, making React apps faster and more efficient by minimizing direct DOM manipulation.

  • Reusable Components: React’s component model enables reusability, which speeds up development and improves maintainability.

  • Rich Ecosystem: React has a large ecosystem with tools like React Router for routing and Redux for state management, along with many libraries and packages tailored for React.

  • One-Way Data Binding: Data flows in a single direction, making it easier to understand and debug.

  • Example of a Functional Component

    Here's a simple counter component in React using hooks:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Current Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;

React Ecosystem in Practice

If you're working on larger applications, you might incorporate libraries like:

  • React Router: For managing routes in a React application.

  • Redux (or Zustand, Recoil): For complex global state management, though the Context API and hooks often suffice for simpler cases.

  • Styled-Components or CSS Modules: For styling components in a scoped and organized manner.

React’s flexibility and component-based approach make it a preferred choice for modern front-end development, particularly with SPA and complex, interactive UIs.

LifeCycle

To handle lifecycle events in functional components with React hooks, we use the useEffect hook. This hook combines the functionality of several class component lifecycle methods, allowing you to run side effects (e.g., data fetching, subscriptions, timers) in functional components.

Here’s a breakdown of how useEffect can mimic each lifecycle method:

  • Mounting: useEffect without dependencies acts like componentDidMount.

  • Updating: useEffect with dependencies acts like componentDidUpdate.

  • Unmounting: Returning a cleanup function in useEffect acts like componentWillUnmount.

  • Example: Counter Component Using useEffect

  • Here’s an example showing how useEffect can be used to replicate class lifecycle methods in a functional component:

  •       import React, { useState, useEffect } from 'react';
    
          function Counter() {
            const [count, setCount] = useState(0);
    
            // Mimicking componentDidMount
            useEffect(() => {
              console.log('Component mounted');
    
              // Mimicking componentWillUnmount (cleanup function)
              return () => {
                console.log('Component will unmount');
              };
            }, []); // Empty dependency array means it runs only once on mount and unmount
    
            // Mimicking componentDidUpdate
            useEffect(() => {
              console.log('Component updated - count changed:', count);
            }, [count]); // Runs every time `count` changes
    
            const increment = () => setCount((prevCount) => prevCount + 1);
    
            return (
              <div>
                <p>Current Count: {count}</p>
                <button onClick={increment}>Increment</button>
              </div>
            );
          }
    
          export default Counter;
    

    Explanation

    1. Mimicking componentDidMount:

      • The first useEffect has an empty dependency array ([]), so it runs only once when the component mounts.

      • The return statement inside useEffect provides a cleanup function, which runs when the component unmounts, mimicking componentWillUnmount.

    2. Mimicking componentDidUpdate:

      • The second useEffect depends on [count]. This means it will re-run every time count changes, similar to componentDidUpdate in class components.

      • Here, it logs the current count value whenever it updates.

How useEffect Replaces Multiple Lifecycle Methods

  • By setting different dependencies, useEffect can behave like both componentDidMount and componentDidUpdate.

  • For side effects requiring cleanup, useEffect provides a way to handle unmounting with a return function, making it easy to manage resources (like event listeners or subscriptions).

Using useEffect for Asynchronous Side Effects

  • For API calls or other asynchronous side effects, you’d typically use useEffect with an empty dependency array for a one-time data fetch on mount:

  •       useEffect(() => {
            const fetchData = async () => {
              const response = await fetch('https://api.example.com/data');
              const result = await response.json();
              console.log(result);
            };
    
            fetchData();
          }, []); // Runs only once on mount
    

Conclusion:

In a functional component using React hooks, the useEffect hook handles most lifecycle events, with different configurations representing each stage:

Functional Component Lifecycle (with useEffect)
├── Mounting
│   └── useEffect(() => { /* initialization code */ }, [])
│
├── Updating
│   └── useEffect(() => { /* update code */ }, [dependencies])
│
└── Unmounting
    └── useEffect(() => {
           return () => { /* cleanup code */ };
         }, [])

More from this blog

E

Essential programming concepts

54 posts

I'm a software engineer who is highly interested in TypeScript/ JavaScript. My tech stack has been full-stack TS such as React, Angular with TypeScript/JavaScript and NodeJS.