This is a nice article and the final UX is really nice.
There are a few drawbacks to the ref-based implementation:
- Creating one ref for each header can be impractical to implement in more complex apps, especially if you separate the nav component from the article component. You’d have to figure out how to pass the refs from each Article component to your Nav component. One way to do it would be to use a Context where each heading could register its ref as a possible “scroll to" destination after rendering, and then unregister when unmounting, via the useEffect hook.
- The benefit of the `h1 id` / `a href` approach is that it allows deep-linking to a particular heading via the URL fragment. e.g. https://example.com/home#about will link you to the “About” heading (this is built-in browser behavior). By using refs, just be aware that you lose out on this benefit.
Personally, instead of using refs, I find it more practical to stick to the id/href approach and use plain JS with `getElementById` to compute the scroll position. You can preventDefault on link click to accomplish this.