DEV Community


Discussion on: Mutable and immutable useRef semantics with React & TypeScript

nicholasboll profile image
Nicholas Boll • Edited

I'd probably argue there should be a useMutableRef and useRef rather than complicated types to communicate intent. I often have these small functions that map to normal functions to more clearly communicate intent:

const mutableRef = useMutableRef(false) // mutable, default assigned
const immutableRef = useRef<HTMLInputElement>(null) // React handles this, no default assigned

 * Alias to `useEffect` that intentionally is only run on mount/unmount
const useMount = (callback?: () => void) => {
  React.useEffect(callback, [])
Enter fullscreen mode Exit fullscreen mode

It is even possible to create nice utility functions that make element refs easier to work with:

// util file
function useElementRef<E extends keyof ElementTagNameMap>(element: E) {
  return React.useRef<ElementTagNameMap[E]>(null)

// usage
const ref = useElementRef('div') // React.RefObject<HTMLDivElement>
Enter fullscreen mode Exit fullscreen mode

Notice the theme where the Typescript types start to disappear for normal usage? This means you can still get the benefits of Typescript without explicitly using Typescript. Even JavaScript users of your code can benefit. This technique works better for libraries, especially if you have JavaScript users of your library. You can use JSDoc to explicitly type JS code, but that is a pain for non-primitive types.

I say there doesn't need to be a tradeoff between Typescript gifts and expressing intent. If your team only uses Typescript and understands all the types in use, maybe you don't need to spend any extra time communicating intent through functions. But it is very useful for JavaScript users in addition to Typescript users who don't spend time finding out all the nuances of Typescript type differences like useRef. You have to learn something extra either way (type differences or which function to use), but why not communicate intent explicitly through names vs types?

Thread Thread
fchaplin profile image
Frederic CHAPLIN

Because in this example case Typescript may :

  • throw exceptions at compile time
  • and give intent to the reader
  • without adding more code.