Language Notes

React

Components, hooks, state management, React Router, and best practices for building modern web UIs.

Back to Resources

Basics

React is a JavaScript library for building user interfaces using a component-based architecture.

Creating a React App
npx create-react-app my-app
cd my-app
npm start

# Or with Vite (recommended)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

Components & JSX

Functional Components
function Welcome({ name }) {
  return <h1>Hello, {name}!</h1>;
}

// Arrow function variant
const Card = ({ title, children }) => (
  <div className="card">
    <h2>{title}</h2>
    {children}
  </div>
);

// Usage
<Welcome name="Aditya" />
<Card title="My Card"><p>Content here</p></Card>

Hooks

useState & useEffect
import { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `Count: ${count}`;
    return () => {
      // cleanup on unmount / re-run
    };
  }, [count]); // runs when count changes

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(c => c + 1)}>
        Increment
      </button>
    </div>
  );
}

Other Common Hooks

  • useRef Access DOM elements or persist values
  • useContext Share state across the component tree
  • useMemo Memoize expensive computations
  • useCallback Memoize event handlers
  • useReducer Complex state logic

React Router

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

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

Best Practices

  • Keep components small and focused (single responsibility)
  • Lift state up to the nearest common ancestor
  • Use keys properly in lists (key={item.id})
  • Prefer controlled components for forms
  • Use fragments (<>...</>) to avoid extra DOM nodes
  • Fetch data in useEffect with cleanup
  • Avoid inline object/function creation in JSX (use useMemo/useCallback)
  • Structure folders by feature, not file type