Ravinder Kumar Pant’s Post

The React pattern that has saved me the most time: custom hooks for shared logic. Not parts. Hooks. This is what kept happening to me: Several parts needed the same logic, like getting data, keeping track of the window size, and managing form state. I was copying and pasting useEffect and useState blocks all over the place. The solution is to put the logic into a custom hook. function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handler = () => setWidth(window.innerWidth); window.addEventListener('resize', handler); return () => window.removeEventListener('resize', handler); }, []); return width; } Now any component that needs the window width just calls: const width = useWindowWidth(); All of the cleanup logic, the event listener, and the state are taken care of in one place. What gets different: - Bugs are fixed once, not in five places. - Components are easier to read and understand. - It's easier and more isolated to test the logic. React becomes truly compositional when you utilize custom hooks. What is a custom hook you've made that you use all the time? #React #FrontendDeveloper #JavaScript #WebDev #ReactHooks

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories