What is a typical use case for creating a custom hook in React?
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: "To share reusable logic between components". Custom hook là một hàm có tên bắt đầu bằng use, bên trong gọi các hook khác như useState, useEffect, để đóng gói một đoạn logic có state, ví dụ useFetch, useLocalStorage hay useWindowSize, rồi dùng lại ở nhiều component; mỗi component gọi nó có state riêng, tức là chia sẻ logic chứ không chia sẻ dữ liệu. "To avoid using state in functional components" sai vì custom hook thường chính là nơi chứa state. "To handle side-effects like fetching data" là việc custom hook có thể bọc lại, nhưng chính useEffect mới xử lý side effect; lý do để tạo custom hook là tái sử dụng logic đó. "To directly manipulate DOM elements" sai vì thao tác DOM trực tiếp đi qua useRef và nên hạn chế, không phải mục đích điển hình của custom hook.
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