0Pricing
React Native Academy · บทเรียน

useReducer สำหรับตรรกะสถานะที่ซับซ้อน

แทนที่การเรียก useState หลายครั้งด้วย useReducer เดียว เขียนฟังก์ชันรีดิวเซอร์พร้อมประเภทการกระทำ และส่งการกระทำจากเหตุการณ์ส่วนติดต่อผู้ใช้

useReducer สำหรับตรรกะสถานะที่ซับซ้อน เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why useReducer?

When a component has several useState calls whose updates are interrelated, the logic can become hard to follow. useReducer centralizes all state transitions in a single reducer function, making complex state logic easier to understand, test, and debug — the same pattern made popular by Redux.

The Reducer Function

A reducer is a pure function that takes the current state and an action object, and returns the next state. It must be pure — no side effects, no API calls, no mutations of the incoming state object. Return a new object for the new state. The action.type string identifies what transition to perform.

function counterReducer(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:
      return state;
  }
}

Calling useReducer

useReducer takes the reducer function and an initial state, and returns [state, dispatch]. The state is the current state value. The dispatch function sends an action to the reducer to trigger a state transition and schedule a re-render.

import { useReducer } from 'react';

const initialState = { count: 0 };

function Counter() {
  const [state, dispatch] = useReducer(counterReducer, initialState);

  return (
    <View>
      <Text>Count: {state.count}</Text>
      <Button title='+' onPress={() => dispatch({ type: 'increment' })} />
      <Button title='-' onPress={() => dispatch({ type: 'decrement' })} />
      <Button title='Reset' onPress={() => dispatch({ type: 'reset' })} />
    </View>
  );
}

Passing Payload with Actions

Actions can carry additional data in a payload property. The reducer reads action.payload to know the specifics of the transition. For example, an 'addItem' action can carry the new item's data in its payload, which the reducer appends to the state's items array.

function listReducer(state, action) {
  switch (action.type) {
    case 'addItem':
      return { items: [...state.items, action.payload] };
    case 'removeItem':
      return { items: state.items.filter((i) => i.id !== action.payload.id) };
    default:
      return state;
  }
}

// Dispatch with payload
dispatch({ type: 'addItem', payload: { id: '1', text: 'Buy milk' } });

Managing a Shopping Cart

A shopping cart is a great real-world use case for useReducer because it involves multiple related state transitions: adding items, removing items, updating quantities, and clearing the cart. Each action type maps to a clear, testable transition in the reducer function.

const initialCartState = { items: [], total: 0 };

function cartReducer(state, action) {
  switch (action.type) {
    case 'ADD':
      return {
        items: [...state.items, action.payload],
        total: state.total + action.payload.price,
      };
    case 'CLEAR':
      return initialCartState;
    default:
      return state;
  }
}

Initializing State Lazily

Pass a third argument to useReducer — an init function — to compute the initial state lazily. React calls init(initialArg) instead of using initialArg directly. This is useful when the initial state is derived from a prop or requires an expensive computation.

function init(initialCount) {
  return { count: initialCount };
}

function Counter({ startCount }) {
  const [state, dispatch] = useReducer(
    counterReducer,
    startCount, // passed to init
    init         // called once on mount
  );
}

useReducer vs useState

Use useState for simple, independent values (a boolean, a string, a number). Reach for useReducer when state transitions depend on multiple values at once, when the next state depends on the current state in complex ways, or when you want to co-locate all state logic in one testable function.

// useState — fine for simple independent values
const [name, setName] = useState('');
const [age, setAge] = useState(0);

// useReducer — better when these fields relate to each other
const [userForm, dispatch] = useReducer(userFormReducer, {
  name: '',
  age: 0,
  isValid: false,
});

Form State with useReducer

A complex registration form with many fields and validation logic benefits from useReducer. Define action types like 'CHANGE_FIELD', 'VALIDATE', and 'SUBMIT'. The reducer handles all field updates and validation in one place instead of scattered across multiple useState setters and useEffect calls.

function formReducer(state, action) {
  switch (action.type) {
    case 'CHANGE_FIELD':
      return {
        ...state,
        values: { ...state.values, [action.field]: action.value },
        errors: { ...state.errors, [action.field]: null },
      };
    case 'SET_ERROR':
      return { ...state, errors: { ...state.errors, ...action.errors } };
    default:
      return state;
  }
}

Testing a Reducer in Isolation

Because reducers are pure functions with no side effects, they are extremely easy to unit test. Call the reducer directly with a state and an action, and assert on the returned state. You do not need to mount any component or mock any API to test the logic.

// Pure unit test — no React needed
test('increment action increases count by 1', () => {
  const state = { count: 5 };
  const next = counterReducer(state, { type: 'increment' });
  expect(next.count).toBe(6);
});

test('reset returns count to 0', () => {
  const state = { count: 100 };
  const next = counterReducer(state, { type: 'reset' });
  expect(next.count).toBe(0);
});

Combining useReducer with useContext

A powerful pattern is pairing useReducer with useContext to build a mini Redux-like global store. Export the dispatch function via context so any descendant component can dispatch actions without prop drilling. This avoids installing a third-party library for moderate complexity apps.

const StoreContext = createContext(null);
const DispatchContext = createContext(null);

export function StoreProvider({ children }) {
  const [state, dispatch] = useReducer(appReducer, initialState);
  return (
    <StoreContext.Provider value={state}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </StoreContext.Provider>
  );
}

Dispatching from Multiple Components

With the dispatch function available via context, any nested component can trigger state transitions without receiving props. Import the useContext(DispatchContext) hook, call dispatch with the appropriate action type, and the reducer handles the update centrally. This scales well as the app grows.

function AddToCartButton({ product }) {
  const dispatch = useContext(DispatchContext);

  return (
    <Button
      title='Add to Cart'
      onPress={() => dispatch({ type: 'ADD', payload: product })}
    />
  );
}

Quick Check

Test your understanding of useReducer for complex state logic from this lesson.

Lesson Recap

In this lesson you learned: useReducer centralizes state transitions in a pure reducer function, dispatch actions with a type and optional payload to trigger transitions, and pair useReducer with useContext for a scalable global state pattern without Redux. Next up we explore useCallback and useMemo for performance optimization.

คำถามที่พบบ่อย

บทเรียน “useReducer สำหรับตรรกะสถานะที่ซับซ้อน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “useReducer สำหรับตรรกะสถานะที่ซับซ้อน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “useReducer สำหรับตรรกะสถานะที่ซับซ้อน”

แทนที่การเรียก useState หลายครั้งด้วย useReducer เดียว เขียนฟังก์ชันรีดิวเซอร์พร้อมประเภทการกระทำ และส่งการกระทำจากเหตุการณ์ส่วนติดต่อผู้ใช้ คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “useReducer สำหรับตรรกะสถานะที่ซับซ้อน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม

ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. useRef สำหรับโหนด DOM และค่าที่เปลี่ยนแปลงได้
  2. useReducer สำหรับตรรกะสถานะที่ซับซ้อน
  3. useCallback และ useMemo เพื่อประสิทธิภาพ
  4. การเขียนฮุกแบบกำหนดเอง
← กลับไปที่ React Native Academy