top | item 20932802

(no title)

dumbmatter | 6 years ago

Tons of shitty "here's how to use hooks for X" articles on Medium make the mistake, so people learning hooks right at the beginning will not be completely immune.

Also that the fix is "instead of using this one kind ref, use another kind of ref and put it in state"... I don't know, like I said I'm not sure if there is a better solution, but it still feels kind of unintuitive and complicated.

Now that I'm thinking about it... what is the reason that DOM refs and other refs need to be handled by the same concept? Every time I make a DOM ref, I'm doing something with it in a hook like useEffect. Why make me jump through hoops to re-run the hook if the DOM ref changes?

(I recognize there are probably good answers to those questions, the React folks are great, I just don't know the answers! Is it just to avoid introducing one more "type of thing", and instead making refs and DOM refs the same "thing"?)

discuss

order

PKop|6 years ago

What is the use case for re-rendering based on change of DOM ref? (that can't be accomplished by putting some data in state?)

Ref's are basically a 1 to 1 replacement for instance fields for mutable data (that doesn't cause rerenders).

https://reactjs.org/docs/hooks-reference.html#useref

There's always need for escape hatches and maybe I'm missing your use case, but in the context of a discussion about how hooks are more complicated than classes, what were you doing before with refs to solve your "re-render" on change scenario?

Your example was likely contrived, but modifying innerHTML should be replaced by putting whatever in state and simply rendering it. And use state for dependencies where you want to re-run on change. Refs are just another way to keep state but not have it affect render cycle.

dumbmatter|6 years ago

Stuff like https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-...

If you're not aware of that, it is very tempting to use `useRef`, which is what I have often seen. Before hooks, we did not have the temptingly-named footgun `useRef` for this scenario (although we did have other footguns for other scenarios, and overall I love hooks).