React: Core Concepts and Hooks

React is a JavaScript library for building user interfaces (UI), using declarative (Declarative) and componentized (Component-Based) development models.

The core idea of React is: UI is the function of State and Props. The developer describes what the interface should look like in different states, and React is responsible for coordinating component updates and applying the necessary changes to DOM.

The main concepts of React include:

  • Component、JSX、Props。
  • State、Events、Conditional Rendering。
  • Rendering、Reconciliation、Keys。
  • Hooks: useState, useEffect, useRef, useMemo, useCallback, useContext, etc.

1. Component: Component

The React application consists of multiple Component. Modern React mainly uses Function Component.

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

export default function App() {
  return (
    <main>
      <Greeting />
    </main>
  );
}

A component is essentially a function that returns React Elements, and the name usually starts with a capital letter.

Core features:

  • Reusable: Components can be reused.
  • Composable: Components can be nested and combined.
  • Declarative: Describes UI based on the input, rather than manually modifying DOM.
  • Isolated State: Different component instances can maintain their own states.

For example, if the same Counter component is rendered twice, there are usually two independent copies of State.

2. JSX: Declarative UI

JSX is a syntactic extension of JavaScript that allows UI to be described within JavaScript/TypeScript.

const name = "Alice";

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

{} is used to embed the JavaScript expression within JSX.

JSX Common Rules

  • Must return a root element, or use Fragment.
  • Labels must be closed correctly.
  • class of HTML is written as className.
  • Events are usually named in camel case, such as onClick.
  • The JavaScript expression is embedded via {}.
function App() {
  return (
    <>
      <h1 className="title">Hello</h1>
      <p>React Application</p>
    </>
  );
}

Fragment (<>...</>) can combine multiple elements without adding additional DOM nodes.

3. Props: Transfer data between components

Props is the data passed by the parent component to the child component.

type UserCardProps = {
  name: string;
  age: number;
};

function UserCard({ name, age }: UserCardProps) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
    </div>
  );
}

function App() {
  return <UserCard name="Alice" age={25} />;
}

Features of Props

  • Data is usually passed down the component tree.
  • Subcomponents cannot directly modify the received Props.
  • Props can be a string, object, array, function, or React Node.
  • The component can be re-rendered when Props changes.

children

children is used for component combination.

import type { ReactNode } from "react";

function Card({ children }: { children: ReactNode }) {
  return <div className="card">{children}</div>;
}

function App() {
  return (
    <Card>
      <h2>Title</h2>
      <p>Content</p>
    </Card>
  );
}

An important design principle of React is Composition over Inheritance (composition over inheritance).

Pass events to parent component

Child components can notify parent components through function Props:

function Child({ onSave }: { onSave: () => void }) {
  return <button onClick={onSave}>Save</button>;
}

function Parent() {
  function handleSave() {
    console.log("Saved");
  }

  return <Child onSave={handleSave} />;
}

This is not a reverse pass of State, but the parent component passes the callback function to the child component to call.

4. State: component status

State is used to save data that changes with user interaction or application logic.

The most commonly used of React is useState().

import { useState } from "react";

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

  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

useState() returns:

const [state, setState] = useState(initialValue);
  • state: The current status value of Render.
  • setState: Request React to update status.

Calling Setter will not directly modify the variables in the current Render, but will trigger subsequent rendering.

State is Snapshot

For example:

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

  function handleClick() {
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
  }

  return <button onClick={handleClick}>{count}</button>;
}

A hit will usually only increment by 1 because the three calls use the same count from the current Render.

Functional Update

If the new state depends on the old state, the functional form should be used:

setCount((prev) => prev + 1);

For example:

function handleClick() {
  setCount((prev) => prev + 1);
  setCount((prev) => prev + 1);
  setCount((prev) => prev + 1);
}

One click will increase by 3.

Object / Array State

When updating objects and arrays, new values should be created and the original State should not be modified directly.

const [user, setUser] = useState({
  name: "Alice",
  age: 25,
});

setUser((prev) => ({
  ...prev,
  age: 26,
}));

Array update:

const [items, setItems] = useState<string[]>([]);

setItems((prev) => [...prev, "New Item"]);

setItems((prev) => prev.filter((item) => item !== "Old Item"));

React uses mechanisms such as reference equality to determine whether partial status updates need to continue processing, so immutable updates are very important.

5. Event Handling: event processing

React uses event handlers to respond to user interaction.

function Button() {
  function handleClick() {
    console.log("Clicked");
  }

  return <button onClick={handleClick}>Click</button>;
}

Note the difference:

onClick={handleClick}   // transfer function
onClick={handleClick()} // Called immediately when rendering

Event Object

function Input() {
  function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    console.log(event.target.value);
  }

  return <input onChange={handleChange} />;
}

Event Propagation

React events typically bubble up along the component's DOM structure.

function App() {
  return (
    <div onClick={() => console.log("Parent")}>
      <button
        onClick={(event) => {
          event.stopPropagation();
          console.log("Child");
        }}
      >
        Click
      </button>
    </div>
  );
}

Commonly used methods:

  • event.stopPropagation(): Prevent further spread.
  • event.preventDefault(): Prevent default behavior.

6. Conditional Rendering and Lists

Conditional rendering

function Status({ loading }: { loading: boolean }) {
  if (loading) {
    return <p>Loading...</p>;
  }

  return <p>Completed</p>;
}

You can also use conditional expressions:

{
  isLoggedIn ? <Dashboard /> : <Login />;
}

and:

{
  showDetails && <Details />;
}

List rendering

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];

function UserList() {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

The role of key

key helps React identify the identities of different elements in the same hierarchy.

Requirements:

  • Key at the same level should be unique.
  • Key should remain stable between re-renders.
  • Priority is given to using stable identifiers such as database ID.

It is not recommended to use array indexes as Key in dynamic lists because deletion, insertion, or reordering may cause State misalignment.

key is not passed into the component as a normal Props.

7. Rendering and Reconciliation

React update UI can be summarized as:

State / Props Change
        ↓
Render Phase
        ↓
Reconciliation
        ↓
Commit Phase
        ↓
DOM Updated

Render Phase

React calls the component function to calculate the new React Element Tree.

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

  console.log("Rendering");

  return <p>{count}</p>;
}

Re-executing the component does not necessarily mean that the real DOM will be modified.

Reconciliation

React Compare the old and new rendering results to determine which nodes need to be retained, updated or replaced.

Component type, position, and key all affect the determination of element identity.

Commit Phase

React commits the necessary changes to DOM.

The browser is then responsible for layout, drawing, etc.

State Preservation

The same component type, React, will usually retain its State if it continues in the same position in the component tree.

If you need to force a reset:

<Profile key={userId} userId={userId} />

When userId changes, the change in key causes React to treat it as a new component instance, thus resetting the internal State.

8. useEffect: Side effects

useEffect() is used to synchronize components with React external systems.

Common scenarios:

  • Subscribe to events.
  • Operating browser API.
  • Connect WebSocket.
  • Set and clean up timers.
  • Integrates with third-party non-React components.
import { useEffect } from "react";

function Example() {
  useEffect(() => {
    console.log("Effect setup");

    return () => {
      console.log("Effect cleanup");
    };
  }, []);

  return <div>Example</div>;
}

Dependency Array

useEffect(() => {
  // ...
});

No Dependency Array: Effect will be re-executed after each commit.

useEffect(() => {
  // ...
}, []);

Empty array: will not be re-executed due to Props/State update, but will still be executed when the component is remounted.

useEffect(() => {
  // ...
}, [userId]);

Resync when userId changes.

Cleanup

For example, subscribing to browser events:

useEffect(() => {
  const handleResize = () => {
    console.log(window.innerWidth);
  };

  window.addEventListener("resize", handleResize);

  return () => {
    window.removeEventListener("resize", handleResize);
  };
}, []);

Cleanup is run before Effect is re-executed and when the component is uninstalled.

Don't abuse useEffect

If the data can be calculated from the existing State and Props, there is usually no need for an additional Effect.

Not recommended:

const [firstName, setFirstName] = useState("Alice");
const [lastName, setLastName] = useState("Smith");
const [fullName, setFullName] = useState("");

useEffect(() => {
  setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);

Recommended:

const fullName = `${firstName} ${lastName}`;

useEffect Lifecycle callbacks are not required for all state changes. It is mainly responsible for synchronization with external systems rather than general data calculations.

StrictMode

In development mode, StrictMode may additionally execute Setup / Cleanup of Effect to discover problems where resources are not properly cleaned up.

This is a development check mechanism and does not mean that the production environment will be repeated in the same way.

9. useRef: mutable reference

useRef() is used to hold mutable values that persist across Render.

import { useRef } from "react";

function Example() {
  const countRef = useRef(0);

  function handleClick() {
    countRef.current += 1;
    console.log(countRef.current);
  }

  return <button onClick={handleClick}>Click</button>;
}

The difference from useState:

ContrastuseStateuseRef
Save cross-render dataYesYes
Trigger rerender after updateusuallyNo
PurposeUI statusDOM reference, non-rendered data
Update methodSetter.current

DOM Reference

One of the most common uses:

function SearchInput() {
  const inputRef = useRef<HTMLInputElement>(null);

  function focusInput() {
    inputRef.current?.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus</button>
    </>
  );
}

useRef is suitable for saving variable data that is not directly involved in the output of UI.

Do not rely on modifying .current to update the interface, as it will not trigger React Render.

10. useMemo: cache calculation results

useMemo() is used to cache calculation results to avoid repeated execution of more expensive calculations when dependencies have not changed.

import { useMemo } from "react";

function ProductList({
  products,
  keyword,
}: {
  products: { id: number; name: string }[];
  keyword: string;
}) {
  const filteredProducts = useMemo(() => {
    return products.filter((product) => product.name.includes(keyword));
  }, [products, keyword]);

  return (
    <ul>
      {filteredProducts.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

Basic syntax:

const value = useMemo(() => expensiveCalculation(a, b), [a, b]);

Need to pay attention to:

  • useMemo is a performance optimization, not a data correctness mechanism.
  • Caching is not guaranteed forever.
  • It is usually not necessary for simple calculations.
  • Recalculation is required when dependencies change.

New versions of React and React Compiler may automatically optimize some calculations, but manual Memoization can still be used for clear performance bottlenecks.

11. useCallback: Cache function reference

useCallback() is used to keep function references relatively stable when dependencies do not change.

import { useCallback, useState } from "react";

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

  const handleSave = useCallback(() => {
    console.log("Saved");
  }, []);

  return (
    <>
      <button onClick={() => setCount((c) => c + 1)}>{count}</button>
      <Child onSave={handleSave} />
    </>
  );
}

useMemo and useCallback

Hookcache content
useMemo()Calculation result
useCallback()function reference

Both are recalculated via Dependency Array control.

Typical uses:

  • Pass the callback to the memo() optimized child component.
  • Make function references that are dependencies of other Hook stable.
  • Avoid double counting or updating where costs do exist.

useCallback by itself does not make function calls faster, nor does it mean that all event handling functions should be wrapped.

12. useContext: Sharing data across levels

When multiple nested components need to access the same data, you can use Context to reduce the need to pass Props layer by layer.

App
 └── Layout
      └── Header
           └── UserMenu

If UserMenu requires the current topic, use Context to avoid passing theme at every level.

Create Context

import { createContext, useContext } from "react";

type Theme = "light" | "dark";

const ThemeContext = createContext<Theme>("light");

function ThemeLabel() {
  const theme = useContext(ThemeContext);

  return <p>Current theme: {theme}</p>;
}

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

Context Notes

  • Context is suitable for sharing data such as topic, language, user context, etc.
  • A change to value from Provider will cause components using that Context to re-render.
  • Context is not equivalent to a complete global state management tool.
  • Shared states that change frequently and have a large scope may require a more fine-grained state organization.

Context solves the problem of data transmission and does not automatically solve complex status update and performance issues.

13. useReducer: Complex status update

When State contains multiple operations or the update logic is complex, useReducer() can be considered.

import { useReducer } from "react";

type State = {
  count: number;
};

type Action = { type: "increment" } | { type: "decrement" } | { type: "reset" };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return { count: 0 };
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <>
      <p>{state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </>
  );
}

Compare with useState:

  • useState: Suitable for simple and independent states.
  • useReducer: Suitable for multiple Action and complex state transitions.
  • useReducer + useContext: Can organize shared status and update logic across components.

It is not necessary to use Reducer for simple booleans and counters.

14. Custom Hooks: Multiplexed state logic

Custom Hook is a function starting with use that can call other Hooks.

For example, encapsulating the browser window width:

import { useEffect, useState } 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;
}

Use:

function ResponsiveLabel() {
  const width = useWindowWidth();

  return <p>Window width: {width}</p>;
}

This example only applies to browser client rendering; in the SSR environment, the initialization phase cannot directly assume that window exists, and an implementation that adapts to server rendering needs to be used.

The value of Custom Hooks:

  • Reuse state and side-effect logic.
  • Reduce duplicate code in components.
  • Encapsulate interactions with the browser API or external systems.

Note: Multiple components calling the same Custom Hook will still have their own independent State by default and will not automatically share state.

15. Rules of Hooks

React Hooks needs to follow two key rules.

Rule 1: Can only be called at the top level

Hook cannot be called in conditions, loops, or ordinary nested functions.

Error:

if (isLoggedIn) {
  const [user, setUser] = useState(null);
}

Correct:

const [user, setUser] = useState(null);

if (!isLoggedIn) {
  return null;
}

This is because React needs to associate component status according to the calling sequence of Hook.

Rule 2: Only call it in React function component or Custom Hook

It cannot be called arbitrarily in the ordinary JavaScript function.

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

  return { count, setCount };
}

Also follow:

  • Avoid side effects in Render.
  • Props and State are not modified directly.
  • Effect dependencies should contain the reactive values used.
  • Use eslint-plugin-react-hooks to check the rule.

16. The relationship between React and Next.js

React is the UI library, and Next.js is the application framework based on React.

React itself does not provide for complete file routing, server-side rendering, data caching, and deployment structures; Next.js provides these framework capabilities on top of React.

In Next.js App Router:

  • Server Components can be executed in a server environment.
  • Client Components supports useState, useEffect and browser interaction.
  • "use client" declares client component module boundaries.
  • Not every file that uses React requires "use client".

For example:

"use client";

import { useState } from "react";

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

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

The boundary between React Hooks and React Server Components is suitable for further explanation in a separate article on Next.js.


Summary

conceptimportance
Component / JSXcore
Props / childrencore
State / Functional Updatecore
Event Handlingcore
Conditional Rendering / Lists / Keyscore
Render / Reconciliation / Commitcore
State Preservation / Resetimportant
useStatecore
useEffect / Cleanupcore
useRefcore
useMemoCommonly used
useCallbackCommonly used
useContextimportant
useReduceron demand
Custom Hooksimportant
Rules of Hookscore

The five most important concepts:

  1. Declarative UI: React describes UI in terms of State and Props, rather than operating directly on DOM.
  2. Rendering: A State update triggers a rerender, but does not necessarily cause a true DOM update.
  3. State Snapshot: Each Render has its own State snapshot, Functional Update should be used when updating dependencies on old values.
  4. Effects: useEffect is mainly responsible for synchronization with external systems, rather than ordinary data calculations.
  5. Hooks: Use state, references and shared context in function components through mechanisms such as useState, useRef, useContext.

After mastering these basics, you can further learn Component Composition, Controlled Components, State Lifting, React.memo and state management modes.

Reference documentation

Back to top