Life Without Callbacks | SitePen


  1. We’re using useEffect to run some code whenever the ref or focused state changes. This will ensure that if a component needs to destroy and recreate DOM nodes (maybe from a key change), we’re always working with the right nodes.
  2. We define a focus/blur handler that will get run on the node’s focus and blur events. Like in the original example, we are simply updating our state based on whether or not the node is in focus.
  3. We are using the imperative DOM APIs to add focus and blur event listeners with our handler.
  4. We want to make sure we clean up our event listeners!


  1. We store the scroll position in state. This allows us to re-render our component on scroll, as well as have access to the latest recorded scroll position.
  2. As with our focus handler, we use useEffect to register / clean up our event listener. This is an easy one, all we want to do is record the last known scroll position.
  3. As simple as this is, this is the crux of the whole hook. By always returning the latest scroll position, we can make reactive decisions on every render.




Modernizing Apps, Tools & Teams | | Twitter: @sitepen

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Modernizing Apps, Tools & Teams | | Twitter: @sitepen