CLASSFUNC BLOG
We Share Our Knowledge
Performance React app với useReducer
JavaScriptReactJS
Dam Van Duong
8 Th03 2021 12:12

Như các bạn đã biết, khi sử dụng useState trong react, nếu trong một component ta khai báo quá nhiều useState, khi setState quá nhiều sẽ dẫn đến việc component bị re-render lại nhiều lần, điều này khiến việc sử dụng app, nhập dữ liệu v.v... bị giật lag và không như mong muốn. Có nhiều cách như sử dụng Form Submit, useContext (trong trường hợp truyền dữ liệu giữa nhiều lớp component), hôm nay mình sẽ giới thiệu cách quản lý state bằng useReducer (ưu tiên khi sử dụng để quản lý state giữa 1-2 component).

Cú pháp sử dụng:

const [state, dispatch] = useReducer(reducer, initialArg, init);

Cùng xem ví dụ sử dụng useReducer của mình nhé:

import React, {useReducer} from "react"; import {TextField} from "@material-ui/core"; import Button from "@material-ui/core/Button"; export const reducer = (state, action) => { switch (action.type) { case 'onUpdate': { return { ...state, id: action.data.id, color: action.data.color, name: action.data.name }; } case 'name': { return {...state, name: action.name}; } case 'name2': { return {...state, name2: action.name2}; } case 'reset': { return { id: null, color: '#000000', name: '', }; } } }; function reducerValues(props) { const [state, dispatch] = useReducer(reducer, { id: null, color: '#000000', name: '' }); return ( <> <TextField id="outlined-name" label="Name" value={state.name} onChange={(event) => dispatch({type: 'name', name: event.target.value})} variant="outlined" /> <TextField id="outlined-name" label="Name 2" value={state.name2} onChange={(event) => dispatch({type: 'name2', name2: event.target.value})} variant="outlined" /> <Button variant="contained" color="primary" onClick={() => dispatch({type: 'onUpdate'})}> Ok </Button> <Button variant="contained" color="secondary" onClick={() => dispatch({type: 'reset'})}> Reset </Button> </> ) }

Với một component sử dụng nhiều biến state khác nhau, khai báo nhiều useState trong một component và thực hiện việc thay đổi state nhiều, nên chuyển qua dùng useReducer để giảm lượng re-render của component lại. UseReducer có thể nói là phiên bản cao cấp hơn của useState, nhận vào input là state để quản lí các state của component, và một hàm action là dispatch, trả về output là một tập hợp các state mới.

Phương thức dispatch phản hồi một hành động của bạn, đã được khai báo trong action của function 'reducer', React qua thuật toán so sánh Object.is đảm bảo rằng, nếu không có sự thay đổi thì react sẽ bỏ qua việc rerender lại các phần tử trong component.

Ở ví dụ trên, chúng ta có các phương thức dispatch riêng cho textField 1, textField2, button Ok, button Reset là các action riêng biệt. Chúng ta có thể thêm các acction khác để quản lý state tránh việc component re-render nhiều lần như khi sử dụng useState.

Ngoài ra cũng có thể sử dụng với useContext, useCallback, useMemo, có thể xem thêm tại : Performance React App Với React.memo , useMemo , useCallback

Tài liệu tham khảo:

https://reactjs.org/docs/hooks-reference.html