Skip to content

MohamedTealeb/React

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 

Repository files navigation

React Documentation (Comprehensive Guide)

This document is a full, practical, and example-rich guide to React — intentionally structured like official documentation but focused on clarity, real-world usage, and modern best practices.


1. Quick Overview

React is a JavaScript library for building user interfaces by composing small, reusable pieces called components. React focuses on the View layer and encourages declarative UI.

Key concepts:

  • Components (functional & class)
  • JSX
  • One-way data flow
  • Hooks
  • Virtual DOM & efficient reconciliation

2. Getting Started

Create a new project (recommended: Vite)

npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

Minimal example

import React from 'react';
import ReactDOM from 'react-dom/client';

function App() {
  return <h1>Hello React</h1>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

3. JSX

JSX looks like HTML but runs in JavaScript. It compiles to React.createElement.

Rules:

  • Must return a single parent element.
  • Use className instead of class.
  • Use htmlFor instead of for.

Example:

const name = 'Amina';
const el = <div className="card">Hello, {name.toUpperCase()}!</div>;

4. Components

Functional Components (preferred)

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

Class Components (legacy)

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

Functional components with hooks are recommended for modern apps.


5. Props & State

  • Props: read-only data passed from parent.
  • State: mutable data inside a component.

Example:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(c => c + 1)}>
      Count: {count}
    </button>
  );
}

6. Hooks

Hooks allow functional components to manage state and lifecycle.

Rules of Hooks

  1. Call hooks only at top level.
  2. Only call them inside React functions.

Common Hooks

  • useState
  • useEffect
  • useRef
  • useMemo
  • useCallback
  • useReducer
  • useContext

useEffect example

useEffect(() => {
  const id = setInterval(() => setTime(t => t + 1), 1000);
  return () => clearInterval(id);
}, []);

Advanced Hooks

  • useLayoutEffect
  • useId
  • useTransition
  • useDeferredValue

7. Component Lifecycle in Depth

React components (especially class components) go through a lifecycle of mounting, updating, and unmounting. Hooks provide equivalents for function components.

Lifecycle Phases

1️⃣ Mounting (Component appears on screen)

Occurs when the component is first rendered.

Step Class Method Function Component Equivalent
Initialize state & props constructor() First render + useState initialization
After component is added to the DOM componentDidMount() useEffect(() => {...}, [])

Example:

useEffect(() => {
  console.log('Mounted');
}, []);

Typical use cases:

  • Fetch API data
  • Subscribe to events
  • Initialize timers

2️⃣ Updating (State/props change)

Happens every time the component re-renders due to changes.

Step Class Method Function Equivalent
Component re-render render() Function body executes again
After update componentDidUpdate() useEffect(..., [deps])

Example:

useEffect(() => {
  console.log('Counter changed:', counter);
}, [counter]);

Use cases:

  • Trigger actions when specific variable changes
  • Sync UI with external system

3️⃣ Unmounting (Removed from the DOM)

Step Class Method Function Equivalent
Component removed componentWillUnmount() cleanup function in useEffect

Example:

useEffect(() => {
  const id = setInterval(() => console.log('Tick'), 1000);
  return () => clearInterval(id); // cleanup on unmount
}, []);

Use cases:

  • Clearing timers
  • Removing event listeners
  • Closing connections

Additional Class Lifecycles

shouldComponentUpdate()

Used to control if component should re-render. Function alternative:

  • React.memo()
  • useCallback
  • useMemo

getDerivedStateFromProps()

Rarely used. Lets state update when props change. Function alternative:

  • manually update state in useEffect

getSnapshotBeforeUpdate()

Called before DOM updates (e.g. capturing scroll position). Function alternative:

  • useLayoutEffect()

Lifecycle Cheat Table

Phase Class Function
Before initial render constructor function body + useState
After first render componentDidMount useEffect(..., [])
Before update getDerivedStateFromProps manual logic inside body
Capture DOM info getSnapshotBeforeUpdate useLayoutEffect
After update componentDidUpdate useEffect(..., [deps])
Before destroy componentWillUnmount cleanup function

Summary

Hooks unify lifecycle into simpler logic:

  • useEffect = mount + update + unmount
  • useLayoutEffect = runs synchronously before browser paint
  • Class lifecycle methods are still supported but not recommended for new projects.

7.1 Lifecycle Flowchart (Conceptual)

Below is how React lifecycle flows for class components:

            MOUNTING
-----------------------------------
constructor() → render() → componentDidMount()
                                         ↓
                                      UPDATE
-----------------------------------
new props or setState()
         ↓
shouldComponentUpdate() → render() → componentDidUpdate()
                                         ↓
                                      UNMOUNT
-----------------------------------
componentWillUnmount()

Functional Component Equivalent:

function render() { ... }
useEffect(() => {...}, [])   → mount
useEffect(() => {...}, [deps]) → update
cleanup return → unmount

7.2 Class vs Function Components

Feature Class Components Function Components (Hooks)
State this.state useState
Update logic setState() State setter (e.g. setCount)
Lifecycle Many lifecycle methods useEffect for all side effects
Refs createRef() useRef()
Code size Verbose Smaller & simpler
Logic sharing HOCs & Render Props Custom Hooks
Recommended ❌ Legacy ✔ Modern standard

7.3 Common React Lifecycle Interview Questions

❓ What happens first: render() or componentDidMount()?

  • render() runs first.
  • componentDidMount() runs after the component is added to the DOM.

❓ Can you set state inside componentDidUpdate()?

Yes — but you must wrap it in a conditional to avoid infinite loops.

❓ What is the Hooks equivalent of componentWillUnmount()?

The return cleanup function inside useEffect.

❓ Does useEffect run before or after paint?

  • useEffect runs after the browser paints.
  • useLayoutEffect runs before paint.

❓ Why is componentWillMount unsafe?

  • It can run multiple times in async mode.
  • React officially deprecated it.

❓ Can you directly call lifecycle methods?

No — React manages them internally.


7.4 How React Rendering & Reconciliation Works

React uses a virtual DOM and a diffing algorithm to update the UI efficiently.

Virtual DOM

  • React keeps an in-memory copy of the UI.
  • When state changes → React recalculates a new Virtual DOM.
  • Then compares old vs new.

Diffing Algorithm

Rules:

  1. If an element type changes (e.g. <div><span>) → React removes and re-renders.
  2. If children change, React compares them in order.
  3. Keys help React match elements.

Example:

Bad key usage

items.map((item, index) => <li key={index}>{item.name}</li>);

Good key usage

items.map(item => <li key={item.id}>{item.name}</li>);

Fiber Architecture (Modern React)

React rebuilds work in small units:

  • Allows rendering to be paused, resumed, or aborted.
  • Enables concurrency features like useTransition.

Why Concurrency Matters

Without concurrency:

  • Large UI updates block the main thread.

With concurrency:

  • React spreads work over frames.
  • UI stays responsive.

Example:

const [isPending, startTransition] = useTransition();
startTransition(() => {
  setQuery(value);
});

|---| | componentDidMount | useEffect(() => {...}, []) | | componentDidUpdate | useEffect(..., [deps]) | | componentWillUnmount | cleanup inside useEffect |


8. Context API

Share data across components without prop drilling.

const ThemeContext = React.createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function ThemeButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Theme: {theme}</button>;
}

9. Refs, Portals, Error Boundaries

Refs

const inputRef = useRef(null);
<input ref={inputRef} />

Portals

ReactDOM.createPortal(<Modal />, document.body);

Error Boundaries (must be class components)

class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) return <h1>Error occurred</h1>;
    return this.props.children;
  }
}

10. Data Fetching

Classic useEffect

useEffect(() => {
  fetch('/api/users')
    .then(r => r.json())
    .then(setUsers);
}, []);

Recommended

Use libraries like React Query or SWR for caching, refetching, etc.

Server Components

Allow server-side data fetching and reduce client JavaScript.


11. Suspense & Concurrent Features

Suspense

const LazyComp = React.lazy(() => import('./Big'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComp />
    </Suspense>
  );
}

Concurrent Rendering

const [isPending, startTransition] = useTransition();
startTransition(() => setQuery(value));

12. Routing

Popular choices:

  • react-router
  • Next.js
  • Remix

Example:

import { BrowserRouter, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/users" element={<Users />} />
      </Routes>
    </BrowserRouter>
  );
}

13. Build Tools

Modern setups:

  • Vite (recommended)
  • Webpack
  • Turbopack
  • Rollup

CRA is no longer recommended for new apps.


14. Performance

  • Profile with React DevTools
  • Use React.memo for memoizing components
  • Use useMemo / useCallback when needed
  • Virtualize large lists
  • Avoid premature optimization

15. Accessibility (a11y)

  • Prefer semantic HTML
  • Provide screen-reader labels
  • Manage focus (especially in modals)

16. Patterns

Good patterns

  • Small, reusable components
  • Lift state when shared
  • Derive UI from state
  • Use custom hooks to share logic

Anti-patterns

  • Excessive prop drilling
  • Overusing useMemo and useCallback
  • Storing huge objects in state unnecessarily

17. Migration from Classes

  1. Convert render() → return JSX
  2. Replace this.state with hooks
  3. Convert lifecycle methods to useEffect

18. Example: Todo App

function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [text, setText] = useState('');

  function add(e) {
    e.preventDefault();
    setTodos(t => [...t, { id: Date.now(), text }]);
    setText('');
  }

  return (
    <form onSubmit={add}>
      <input value={text} onChange={e => setText(e.target.value)} />
      <button>Add</button>
      {todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
    </form>
  );
}

19. Project Structure Example

my-app/
├─ index.html
├─ src/
│  ├─ main.jsx
│  ├─ App.jsx
│  ├─ components/
│  ├─ hooks/
│  ├─ pages/
│  └─ styles/
└─ package.json

20. Final Notes

This documentation provides a practical overview of modern React development. You can:

  • Use it directly in a GitHub repository
  • Extend it with examples
  • Turn it into a reference for future learning

Happy coding!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors