Frameworks & Libraries

React Basics

React is the most popular UI library in JavaScript. Build interfaces from small, reusable components. Master props, state, effects, and event handling — the core building blocks of every React application.

What is React?

React is a JavaScript library for building user interfaces from components: functions that return JSX (HTML-like syntax) based on their props and state. When state changes with useState, React re-renders the component and updates only what changed in the DOM. It's the most widely used front-end library, and frameworks like Next.js build on it.

import { useState } from "react";

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

Core React Hooks

HookPurposeExample Usage
useStateLocal mutable stateconst [count, setCount] = useState(0)
useEffectSide effects after renderuseEffect(() => { fetch('/api') }, [id])
useRefMutable ref not tied to renderconst inputRef = useRef<HTMLInputElement>(null)
useCallbackMemoize a functionconst fn = useCallback(() => doX(a), [a])
useMemoMemoize an expensive valueconst sorted = useMemo(() => arr.sort(), [arr])
useContextRead context valueconst theme = useContext(ThemeContext)
useReducerComplex state transitionsconst [state, dispatch] = useReducer(reducer, init)
useIdStable unique ID for a11yconst id = useId()

Common Pitfalls

Mutating state directly: state.count++ or array.push() — React doesn't detect this change, no re-render
Always create new references: setCount(c => c + 1), setItems(prev => [...prev, newItem])
Missing dependency in useEffect — stale closure reads old values of state/props
List all variables the effect uses in the dependency array. Use eslint-plugin-react-hooks to catch this.
Using index as key in lists — reordering or inserting causes wrong elements to re-render or persist state
Use stable unique IDs as keys: item.id, item.slug — never array index for dynamic lists.
Calling hooks inside loops, conditions, or nested functions — breaks Rules of Hooks
Always call hooks at the top level of a component or custom hook, unconditionally.

Interactive Demo

Code Editor

<div id="root"></div>

Preview

React Basics: summary

Key points

  • Props flow down from parent to child; children notify parents through callback props.
  • Never mutate state directly; create new objects and arrays ([...items, newItem]).
  • useEffect is for syncing with things outside React (subscriptions, timers), not for deriving data.
  • List items need a stable key prop.

Frequently asked questions

›Should I learn JavaScript before React?

Yes. React is JavaScript: array methods, destructuring, modules, closures and async code are used everywhere in it.

›Is React a framework?

React is a UI library. Frameworks such as Next.js and Remix add routing, data loading and server rendering on top of it.