2026-08-17 14:26

Status:


Common React-Framework Elements

1. Getting Started

Creating a new project (Vite — modern standard):

bash

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

Basic project structure:

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

Entry point (main.jsx):

jsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
 
ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

2. JSX Basics

JSX lets you write HTML-like syntax inside JavaScript.

jsx

function Greeting() {
  const name = "Sam";
  return (
    <div className="greeting">
      <h1>Hello, {name}!</h1>
      {/* comments go in curly braces */}
      <p>{1 + 1} is two.</p>
    </div>
  );
}

Key JSX rules:

  • Use className instead of class
  • Use htmlFor instead of for
  • Every component must return a single root element (or a Fragment)
  • Expressions go inside { }; JS statements (if/for) do not work directly inside JSX

jsx

// Fragments avoid extra wrapper divs
function List() {
  return (
    <>
      <li>Item 1</li>
      <li>Item 2</li>
    </>
  );
}

3. Components

Function Components (standard in modern React)

jsx

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
 
// Arrow function version
const Welcome = ({ name }) => <h1>Hello, {name}</h1>;
 
export default Welcome;

Props (passing data into components)

jsx

function App() {
  return <Welcome name="Alex" age={30} />;
}
 
function Welcome({ name, age }) {
  return <p>{name} is {age} years old</p>;
}
 
// Default props
function Welcome({ name = "Guest" }) {
  return <p>Hello, {name}</p>;
}
 
// children prop
function Card({ children }) {
  return <div className="card">{children}</div>;
}
// Usage: <Card><p>Inner content</p></Card>

4. Conditional Rendering

jsx

function Status({ isLoggedIn }) {
  // if/else
  if (isLoggedIn) return <p>Welcome back!</p>;
  return <p>Please log in.</p>;
}
 
function Status2({ isLoggedIn }) {
  // ternary
  return <p>{isLoggedIn ? "Welcome back!" : "Please log in."}</p>;
}
 
function Notification({ count }) {
  // logical && (renders nothing if false/0/null/undefined)
  return <div>{count > 0 && <span>{count} new messages</span>}</div>;
}

5. Rendering Lists

jsx

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

Always provide a unique key prop when rendering lists — it helps React track which items changed. Avoid using array index as the key if the list can reorder.


6. State — useState

jsx

import { useState } from 'react';
 
function Counter() {
  const [count, setCount] = useState(0);
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={() => setCount((prev) => prev - 1)}>-1</button>
    </div>
  );
}

Updating objects/arrays in state (never mutate directly):

jsx

const [user, setUser] = useState({ name: "Jo", age: 30 });
 
// correct — spread to create a new object
setUser((prev) => ({ ...prev, age: prev.age + 1 }));
 
const [items, setItems] = useState([1, 2, 3]);
 
setItems((prev) => [...prev, 4]);              // add
setItems((prev) => prev.filter((i) => i !== 2)); // remove

7. Event Handling

jsx

function Form() {
  const handleClick = (e) => {
    console.log("Clicked!", e.target);
  };
 
  const handleChange = (e) => {
    console.log(e.target.value);
  };
 
  return (
    <div>
      <button onClick={handleClick}>Click Me</button>
      <input onChange={handleChange} />
      {/* passing arguments to a handler */}
      <button onClick={() => handleClick("extra info")}>Click</button>
    </div>
  );
}

Handling form submission:

jsx

function LoginForm() {
  const [email, setEmail] = useState("");
 
  const handleSubmit = (e) => {
    e.preventDefault(); // stop page reload
    console.log("Submitted:", email);
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button type="submit">Log In</button>
    </form>
  );
}

8. useEffect — Side Effects

jsx

import { useEffect, useState } from 'react';
 
function Example() {
  const [count, setCount] = useState(0);
 
  // Runs after every render
  useEffect(() => {
    console.log("Rendered");
  });
 
  // Runs only once, on mount (empty dependency array)
  useEffect(() => {
    console.log("Mounted");
  }, []);
 
  // Runs when `count` changes
  useEffect(() => {
    console.log("Count changed:", count);
  }, [count]);
 
  // Cleanup function (runs before unmount / before next effect run)
  useEffect(() => {
    const timer = setInterval(() => console.log("tick"), 1000);
    return () => clearInterval(timer);
  }, []);
 
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Fetching data with useEffect:

jsx

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
 
  useEffect(() => {
    async function fetchUsers() {
      try {
        const res = await fetch("https://api.example.com/users");
        const data = await res.json();
        setUsers(data);
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    }
    fetchUsers();
  }, []);
 
  if (loading) return <p>Loading...</p>;
  return (
    <ul>
      {users.map((u) => <li key={u.id}>{u.name}</li>)}
    </ul>
  );
}

9. Other Core Hooks

useRef — persistent value that doesn’t trigger re-render, or DOM access

jsx

import { useRef, useEffect } from 'react';
 
function TextInput() {
  const inputRef = useRef(null);
 
  useEffect(() => {
    inputRef.current.focus(); // direct DOM access
  }, []);
 
  return <input ref={inputRef} />;
}
 
// Storing a mutable value across renders (e.g. previous value, timers)
function Timer() {
  const countRef = useRef(0);
  countRef.current += 1; // doesn't cause re-render
}

useContext — avoid prop drilling

jsx

import { createContext, useContext, useState } from 'react';
 
const ThemeContext = createContext();
 
function App() {
  const [theme, setTheme] = useState("light");
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}
 
function Toolbar() {
  const { theme, setTheme } = useContext(ThemeContext);
  return (
    <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
      Current theme: {theme}
    </button>
  );
}

useMemo — memoize an expensive calculated value

jsx

import { useMemo } from 'react';
 
function ExpensiveList({ items, filter }) {
  const filtered = useMemo(
    () => items.filter((i) => i.includes(filter)),
    [items, filter] // only recompute when these change
  );
  return <ul>{filtered.map((i) => <li key={i}>{i}</li>)}</ul>;
}

useCallback — memoize a function reference

jsx

import { useCallback, useState } from 'react';
 
function Parent() {
  const [count, setCount] = useState(0);
 
  const handleClick = useCallback(() => {
    console.log("Clicked");
  }, []); // stable function reference across renders
 
  return <Child onClick={handleClick} />;
}

useReducer — complex state logic

jsx

import { useReducer } from 'react';
 
function reducer(state, action) {
  switch (action.type) {
    case "increment": return { count: state.count + 1 };
    case "decrement": return { count: state.count - 1 };
    case "reset": return { count: 0 };
    default: throw new Error("Unknown action");
  }
}
 
function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
 
  return (
    <div>
      <p>{state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
    </div>
  );
}

10. Custom Hooks

Reusable logic extracted into your own hook (must start with use):

jsx

import { useState, useEffect } from 'react';
 
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
 
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
 
  return width;
}
 
// Usage in a component
function Display() {
  const width = useWindowWidth();
  return <p>Window width: {width}px</p>;
}

11. Component Composition & Prop Drilling Alternatives

jsx

// Composition via children — avoids tightly-coupled nesting
function Layout({ children }) {
  return (
    <div>
      <Header />
      <main>{children}</main>
      <Footer />
    </div>
  );
}
 
// Usage
<Layout>
  <Dashboard />
</Layout>

12. Forms — Controlled vs Uncontrolled

jsx

// Controlled — React state is the "source of truth" (recommended)
function ControlledInput() {
  const [value, setValue] = useState("");
  return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}
 
// Uncontrolled — DOM manages its own state, accessed via ref
function UncontrolledInput() {
  const inputRef = useRef(null);
  const handleSubmit = () => alert(inputRef.current.value);
  return <input ref={inputRef} />;
}

13. React Router (client-side routing)

bash

npm install react-router-dom

jsx

import { BrowserRouter, Routes, Route, Link, useNavigate, useParams } 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="/users/:id" element={<UserProfile />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}
 
function UserProfile() {
  const { id } = useParams(); // read URL params
  return <p>User ID: {id}</p>;
}
 
function Home() {
  const navigate = useNavigate(); // programmatic navigation
  return <button onClick={() => navigate("/about")}>Go to About</button>;
}

14. Fetching Data / API Calls

jsx

// GET
useEffect(() => {
  fetch("https://api.example.com/items")
    .then((res) => res.json())
    .then((data) => setItems(data));
}, []);
 
// POST
async function createItem(item) {
  const res = await fetch("https://api.example.com/items", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(item),
  });
  return res.json();
}

15. Styling in React

jsx

// Inline styles (object syntax, camelCase properties)
const style = { color: "blue", fontSize: "20px" };
<p style={style}>Styled text</p>;
<p style={{ color: "red" }}>Inline styled</p>;
 
// CSS classes
import './App.css';
<div className="container">Content</div>;
 
// CSS Modules (scoped styles)
import styles from './App.module.css';
<div className={styles.container}>Content</div>;
 
// Conditional classes
<div className={isActive ? "active" : "inactive"}>Item</div>;

16. Performance & Optimization

jsx

// React.memo — skip re-rendering if props haven't changed
const Child = React.memo(function Child({ value }) {
  console.log("Child rendered");
  return <p>{value}</p>;
});
 
// Lazy loading components + Suspense
import { lazy, Suspense } from 'react';
 
const HeavyComponent = lazy(() => import('./HeavyComponent'));
 
function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <HeavyComponent />
    </Suspense>
  );
}

17. Error Handling

jsx

// Error Boundary (must be a class component)
class ErrorBoundary extends React.Component {
  state = { hasError: false };
 
  static getDerivedStateFromError() {
    return { hasError: true };
  }
 
  componentDidCatch(error, info) {
    console.error(error, info);
  }
 
  render() {
    if (this.state.hasError) return <h1>Something went wrong.</h1>;
    return this.props.children;
  }
}
 
// Usage
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

18. Common Patterns Quick-Reference

jsx

// Toggle boolean state
const [isOpen, setIsOpen] = useState(false);
<button onClick={() => setIsOpen((prev) => !prev)}>Toggle</button>
 
// Controlled checkbox
const [checked, setChecked] = useState(false);
<input type="checkbox" checked={checked} onChange={(e) => setChecked(e.target.checked)} />
 
// Controlled select
const [option, setOption] = useState("a");
<select value={option} onChange={(e) => setOption(e.target.value)}>
  <option value="a">A</option>
  <option value="b">B</option>
</select>
 
// Lifting state up (shared between siblings via parent)
function Parent() {
  const [value, setValue] = useState("");
  return (
    <>
      <Input value={value} onChange={setValue} />
      <Display value={value} />
    </>
  );
}

19. Glossary

  • Component — a reusable, self-contained piece of UI, written as a function that returns JSX.
  • Props — data passed from a parent component into a child component (read-only).
  • State — data managed within a component that can change over time and triggers re-renders when updated.
  • Hook — a special function (starting with use) that lets function components use state, lifecycle features, and other React capabilities.
  • JSX — a syntax extension that lets you write HTML-like markup inside JavaScript.
  • Virtual DOM — an in-memory representation of the real DOM that React uses to efficiently calculate and apply UI updates.
  • Key — a special prop used when rendering lists, helping React identify which items changed.
  • Controlled component — a form element whose value is driven by React state.
  • Uncontrolled component — a form element that manages its own state internally, accessed via ref.
  • Lifting state up — moving shared state to the closest common ancestor of the components that need it.
  • Prop drilling — passing props through multiple layers of components to reach a deeply nested child.
  • Context — a way to share values (like themes or auth state) across a component tree without prop drilling.
  • Reconciliation — React’s process of comparing the virtual DOM to determine the minimal set of real DOM updates needed.
  • Memoization — caching a computed value or function so it isn’t recalculated unnecessarily.
  • Side effect — any operation that reaches outside the component (data fetching, subscriptions, manually touching the DOM), typically handled with useEffect.
  • Fragment — a wrapper (<>...</>) that groups elements without adding an extra DOM node.

References