When should the useReducer() Hook be used instead of useState()?
4 phương ánCó giải thích
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "When there is complex state logic, several sub-values, or when the upcoming state depends on the previous state". useReducer gom mọi cách thay đổi state vào một hàm reducer nhận state cùng action và trả về state mới; component chỉ dispatch action mô tả chuyện gì đã xảy ra. Cách này hợp khi state là object có nhiều giá trị con liên quan nhau, khi có nhiều kiểu cập nhật, hoặc khi state kế tiếp tính từ state trước, vì logic nằm tập trung, dễ kiểm thử và tránh các lời gọi set rời rạc làm state mâu thuẫn. "When components require simple, independent state values." là đúng trường hợp nên dùng useState, gọn hơn cho một con số hay một cờ boolean. "When performing initialization and cleanup actions" là việc của useEffect với hàm cleanup trả về. "When sharing data across a component hierarchy without prop" là việc của Context với createContext và useContext, tránh truyền prop qua nhiều tầng.
Cùng phần 6
Find the bug in the following React code: const [items, setItems] = useState([]); const addItem = () => { items.push('new'); setItems(items); };Có lời giảiCâu hỏiWhich is the correct way to consume context in a functional component using the "useContext" hook?Có lời giảiCâu hỏiIn the useEffect hook, how many milliseconds would you wait using setTimeout to perform a side effect after 2 seconds?Có lời giảiCâu hỏiCả 24 câu của chủ đề24 câu