Skip to content

Instantly share code, notes, and snippets.

@thysultan
Last active December 14, 2018 22:44
Show Gist options
  • Save thysultan/c85e017f2805f7e5c11cf3bc0dd9f342 to your computer and use it in GitHub Desktop.
Save thysultan/c85e017f2805f7e5c11cf3bc0dd9f342 to your computer and use it in GitHub Desktop.
Refs
// currentTarget is the current value i.e null/node while target is always the node the ref was attached to
// or vice-versa if matching event target/currentTarget sementics is of any merit.
function subscribe ({currentTarget, target, timeout = setInterval(() => {})}) {
assert(currentTarget instanceof Node || current === null)
assert(target instanceof Node)
// when a function is returned it is used when the ref is unmounted.
return () => setInterval(timeout)
}
// Alternatively a backward compatible direction would be to only implement the return function signature heuristic.
function subscribe (target) {
const timeout = setTimeout(() => {})
return (currentTarget) => {
assert(target instanceof Node)
assert(currrentTarget === null)
setInterval(timeout)
}
}

Function refs are great and all, except they arent really as composable, this is partly because they recieve a single "null" value when unmounting.

If someone also wanted to do something to the referene when unmounting one would need to:

  1. Store the refs when mounting.
  2. Retrieve it when unmounting.

But this inheretly ties us to some statefull abstraction like class components, because storing it in a variable or object with function components traps us into only being able to use the ref function for at most one instance of a component.

However, if we managed to have both the target and currentTarget as a reference we wouldn't need to store the ref.

As a final touch to improve the ergonomics on this front. When a ref function returns a function, the return value(the function) should be used when unmounting. Alternatively this may be exactly/only what we need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment