Understand ReactJS - Part 1 ☘️☘️☘️

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:
useEffectwithout dependencies acts likecomponentDidMount.Updating:
useEffectwith dependencies acts likecomponentDidUpdate.Unmounting: Returning a cleanup function in
useEffectacts likecomponentWillUnmount.Example: Counter Component Using
useEffectHere’s an example showing how
useEffectcan 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
Mimicking
componentDidMount:The first
useEffecthas an empty dependency array ([]), so it runs only once when the component mounts.The
returnstatement insideuseEffectprovides a cleanup function, which runs when the component unmounts, mimickingcomponentWillUnmount.
Mimicking
componentDidUpdate:The second
useEffectdepends on[count]. This means it will re-run every timecountchanges, similar tocomponentDidUpdatein class components.Here, it logs the current count value whenever it updates.
How useEffect Replaces Multiple Lifecycle Methods
By setting different dependencies,
useEffectcan behave like bothcomponentDidMountandcomponentDidUpdate.For side effects requiring cleanup,
useEffectprovides 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
useEffectwith 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 */ };
}, [])



