React Hooks Tutorial - 12 - useReducer API

Опубликовано: 29 Январь 2025
на канале: JAS ACADAMY
127
6

useReducer is used to store and update states, just like the useState Hook. It accepts a reducer function as its first parameter and the initial state as the second.

useReducer returns an array that holds the current state value and a dispatch function, to which you can pass an action and later invoke. This is similar to the pattern Redux uses but with a few differences.

For example, the useReducer function is tightly coupled to a specific reducer. We dispatch action objects to that reducer only, whereas in Redux, the dispatch function sends the action object to the store. At the time of dispatch, the components don’t need to know the reducer that will process the action.

For those who may be unfamiliar with Redux, we’ll explore this concept a bit further. There are three main building blocks in Redux:

A store — an immutable object that holds the applications state data
A reducer — a function that returns some state data, triggered by an action type
An action — an object that tells the reducer how to change the state. It must contain a type property, and it can contain an optional payload property