Comment

Comment by idreyn

I have a hook that I copy around between projects called `useViewport()`. All it does is watch the current viewport size and updates its value when that changes. Because it's a hook, I can call this function from any component body:

  const { width, height}  = useViewport();
  return <div>Viewport: {width} {height}</div>
Zooming in, this is just built from a useEffect() to bind event listeners, and and a useState() to hold the current value. Zooming out, it would be easy to write a useBreakpoint() hook that mostly just calls useViewport(). Hooks compose.

Before hooks, there weren't great patterns for isolating units of stateful logic from the presentational side of React. A really common pattern was to use "render props" where a component keeps some internal state and passes it into a function-as-child:

  <ViewportWatcher>
    {({ width, height}) => <div>Viewport: {width} {height}</div>}
  </ViewportWatcher>
You'd see these provider-components nested three or four layers deep, and it got ugly. Hooks solved this.
parent idreyn 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton