Migrating Instance Variables
This blog post is part of a series on hooks, this blog post assumes you have a decent initial understanding of React Hooks. I highly suggest starting with the ReactJS Docs to learn more.
class based components can have a decent number of instance
variables on them that are unrelated to state or props. These might be used to
store refs for elements, or other data that you may need within the component.
When migrating to Hooks, React offers the
useRef hook, which is a convenient
way to store some mutable data through the lifecycle of a component.
Lets take a look at what this looks like with hooks:
Cool, but when I attempt to access
data.someData.foo I get an error, what
useRef returns you a wrapper around your current value:
We can conceptualize this like the return value of calling
where our variable is accessible on the
Avoid Large Ref Values
This is more of a preference than an actual bug/issue within the code, however
it may be tempting to convert your instance variables all down to a single
While this may look beneficial, and may be easier to access the properties, it makes it potentially more difficult to split up the logic into separate hooks.
In general, always prefer to keep
useState) calls limited in
scope, and bias towards hook composition instead.1
From our first example above, we may want to split the timer instance variable
into a custom
useTimer hook that our component can leverage, and the
inputRef can be accomplished using just a top level
For additional insight into how to
useRef, refer to the
Thanks to Dillon Curry for reviewing an earlier version of this post
Have feedback about this post or questions, don't hesitate to reach out on Twitter (@immatthamlin)!
Follow the discussion on this blog post on twitter.
- I should write yet another blog post about why I have this preference, but for now feel free to accept it as a pattern.↩