Hooks Tips Ep. 2 - Migrating Instance Variables

Published

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.

Frequently, 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.

These values are useful to store on the instance because updating them does not trigger a re-render of the component. Here is an example of a class based component that uses a few instance methods (Note: This is using a non-standard JavaScript syntax to assign the instance variables.):

1class InstanceComponent extends React.Component {
2 someTimer = null;
3 inputRef = null;
4 data = {
5 someData: {
6 foo: 'bar',
7 },
8 };
9
10 // ...
11}
1class InstanceComponent extends React.Component {
2 someTimer = null;
3 inputRef = null;
4 data = {
5 someData: {
6 foo: 'bar',
7 },
8 };
9
10 // ...
11}

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:

1function HookComponent() {
2 const someTimer = React.useRef(null);
3 const data = React.useRef({
4 someData: {
5 foo: 'bar',
6 },
7 });
8
9 // Note, the inputRef is just a regular old element ref
10 // in this case, so we can use `createRef` which will assign
11 // the instance for us. We could also still use `useRef` here and it
12 // will continue to work as expected!
13 const inputRef = React.createRef();
14}
1function HookComponent() {
2 const someTimer = React.useRef(null);
3 const data = React.useRef({
4 someData: {
5 foo: 'bar',
6 },
7 });
8
9 // Note, the inputRef is just a regular old element ref
10 // in this case, so we can use `createRef` which will assign
11 // the instance for us. We could also still use `useRef` here and it
12 // will continue to work as expected!
13 const inputRef = React.createRef();
14}

Cool, but when I attempt to access data.someData.foo I get an error, what gives?

1function HookComponent() {
2 const data = React.useRef({
3 someData: {
4 foo: 'bar',
5 },
6 });
7
8 // ⚠️ This will throw an error:
9 // Unable to access foo of undefined
10 console.log(data.someData.foo);
11}
1function HookComponent() {
2 const data = React.useRef({
3 someData: {
4 foo: 'bar',
5 },
6 });
7
8 // ⚠️ This will throw an error:
9 // Unable to access foo of undefined
10 console.log(data.someData.foo);
11}

Well, useRef returns you a wrapper around your current value:

1console.log(data);
2// { current: { someData: { foo: 'bar' } } }
1console.log(data);
2// { current: { someData: { foo: 'bar' } } }

We can conceptualize this like the return value of calling React.createRef(), where our variable is accessible on the current property.

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 useRef call:

1function UglyHooksComponent() {
2 const instance = React.useRef({
3 someTimer: null,
4 inputRef: React.createRef(),
5 data: {
6 someData: {
7 foo: 'bar',
8 },
9 },
10 });
11}
1function UglyHooksComponent() {
2 const instance = React.useRef({
3 someTimer: null,
4 inputRef: React.createRef(),
5 data: {
6 someData: {
7 foo: 'bar',
8 },
9 },
10 });
11}

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 useRef (and 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 createRef.

For additional insight into how to useRef, refer to the ReactJS Docs

Thanks to Dillon Curry for reviewing an earlier version of this post

I should write yet another blog post about why I have this preference, but for now feel free to accept it as a pattern.

Footnotes