Exploring React Hooks
Hooks provide a means to extract stateful logic from a component, enabling its independent testing and reuse. They pave the way for reutilizing stateful logic without altering your component hierarchy. Essentially, Hooks let you “hook into” React state and other life cycle features from function components.
Following on from the ExpandablePanel
component example, let’s look at this code:
const useAutoClose = (duration: number) => { const [isOpen, setIsOpen] = useState<boolean>(true); useEffect(() => { if (isOpen) { const timerId = setTimeout(() => setIsOpen(false), duration); return () => clearTimeout(timerId); } }, [duration, isOpen]); const toggle = () => setIsOpen((show) => !show); return { isOpen, toggle }; }; export default useAutoClose...