Why React?

In a Single-Page Application (SPA) — a web application that runs on a single HTML page — a Component-Based Architecture is essential for organizing different sections and layouts efficiently.

React enables this by providing a declarative, reusable, and scalable component model that simplifies UI development.


How React Works

Node.js and npm

[!info] npm Commands


App Setup

  1. Create React App (CRA)
    npx create-react-app <appName>
    Slower because it includes full bundling and tooling.

  2. Vite
    npm create vite@latest <appName>
    Faster — uses a modern build tool with optimized dev server.

Key Files

File Purpose
index.html Single HTML page of the SPA
package.json Project metadata, dependencies, and scripts
vite.config.js Vite build configuration
/src Main source folder for React code
main.jsx Entry point, connects React to HTML
App.jsx Root React component
App.css CSS specific to App.jsx
index.css Global CSS for the entire app
index.html  
   ↓  
main.jsx → connects React to the HTML page  
   ↓  
<App.jsx> → root component rendered inside #root  
   ↓  
App.css → component-specific styles  
index.css → global styles

Syntax Overview


Built-In Optimization

React uses a Virtual DOM and Reconciliation.

Steps

  1. React generates a new Virtual DOM after state/props update
  2. It compares it with the previous Virtual DOM
  3. Updates only the necessary changes in the real DOM

Optimization Tips


React Components — Class Components

[!info] Features

Example

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

  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Props

Props are data passed from a parent to a child component.

Passing Functions

When dealing with this, the binding context matters.

Method Example Notes
Constructor binding this.handleClick = this.handleClick.bind(this) Best performance
Arrow class property handleClick = () => {...} Easiest to write
Inline arrow onClick={() => this.handleClick()} OK for small use cases

State

Syntax

this.state = { value: 0 };
this.setState({ value: 1 });
this.setState(prev => ({ value: prev.value + 1 }));

Lifecycle Methods

React class components follow this flow:

constructor()render()componentDidMount()
componentDidUpdate()componentWillUnmount()

Mounting

Updating

Unmounting


React Components — Functional Components

Functional components are simple JavaScript functions that:

[!info] Features

Example code:

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

Hooks Overview

Hooks enable: State, Side effects, Context, Reusable logic (custom hooks)


useState()

const [state, setState] = useState(initialValue);

Updating State

setState(prev => prev + 1);
setUser(prev => ({ ...prev, name: "Jason" }));

useEffect()

Manages side effects: fetching, subscriptions, logging.

Dependency Behavior
none Runs after every render
[] Runs once on mount
[value] Runs when value changes

Cleanup: Executed before re-running the effect:

  1. Check for cleanup
  2. Run cleanup
  3. Run new effect

useReducer()

const [state, dispatch] = useReducer(reducer, initialState);

Reducer

function reducer(state, action) {
  return newState;
}

Rules:

Actions

{ type: "increment" }
{ type: "add_todo", payload: "Buy milk" }

useRef()

const countRef = useRef(0);
countRef.current++;

React Optimization

useMemo()

const sortedList = useMemo(() => sort(list), [list]);

useCallback()

const handleClick = useCallback(() => setCount(c => c + 1), []);

React.memo()

const Child = React.memo(function Child({ value }) {
  return <div>{value}</div>;
});

Lazy Loading

const About = React.lazy(() => import('./About'));
<Suspense fallback={<p>Loading...</p>}>
  <About />
</Suspense>

Controlled vs. Uncontrolled Inputs

Uncontrolled

<input ref={inputRef} />

Controlled

<input value={email} onChange={e => setEmail(e.target.value)} />