A custom React Hook that provides a sensible alternative to `useRef` for storing instance variables.
A custom React Hook that provides a sensible alternative to useRef for storing instance variables.


useRef is weird. The official React docs say:
>useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
>Note that useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.
The fact that you have to access it via .current is strange.
The fact that the React docs call out that you can use it for more than
ref attributes is telling.
They have to know that useRef is confusing too.
That's why I created useInstance.
You treat the object returned by useInstance just like you would this in a class component,
so you're already familiar with how it works.
So… Use useRef if you're dealing with actual DOM elements—useuseInstance for instance properties and methods.
Some may say _"Six of this, hald dozen of another,"_ and they could be right.
But if you're in the "half-dozen" camp, useInstance might well be for you!
``bash`
$ npm i @use-it/instance
or
`bash`
$ yarn add @use-it/instance
Here is a basic setup. Most people will name the returned object
self or that or instance, but you can call it anything you'd like.
`js
import useInstance from '@use-it/instance';
// Then from within your function component
const instance = useInstance(initialInstance);
`
Here are the parameters that you can use. (\* = optional)
| Parameter | Description |
| :---------- | :--------------------------------------------------------------------------------------------------------------- |
| initialInstance | Is an object or a function that returns an object that represents the initial instance value. Defaults to an empty object literal. |
The return value is an object that WILL NOT change on subsequent calls to your function component.
Use it just like you would to create instance properties and methods in a class component.
Here's an example where you might use useRef.useEffect
Within the closure of the , if we simply referencecallback directly, we will see callback as it was during the
creation of the function.
Instead we must make it "live" throughout many render cycles.
`js
function useInterval(callback, delay) {
const savedCallback = useRef();
savedCallback.current = callback;
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
`
And here's the same code using useInstance.self
It has a more familiar class component-like syntax.
Again, think of as this.
`js
function useInterval(callback, delay) {
const self = useInstance();
self.savedCallback = callback;
useEffect(
() => {
function tick() {
self.savedCallback();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
},
[delay]
);
}
`
You can also use useInstance in place of useCallback and useMemo for some cases.
Take for instance (pardon the pun), this simple up/down counter example.
You might use useCallback to ensure that the pointersincrement
to the and decrement function didn't change.
`js
const useCounter = initialCount => {
const [count, setCount] = useState(initialCount);
const increment = useCallback(() => setCount(c => c + 1));
const decrement = useCallback(() => setCount(c => c - 1));
return {
count,
increment,
decrement,
};
};
`
Or, you could store them in the instance, much like you
might have done with a class component.
`js
const useCounter = initialCount => {
const [count, setCount] = useState(initialCount);
const self = useInstance({
increment: () => setCount(c => c + 1),
decrement: () => setCount(c => c - 1),
});
return {
count,
...self,
};
};
`
What is the benefit of keeping functions in instances variable
instead of using useCallback?
This is from the official Hooks documentation.
>In the future, React may choose to “forget” some previously memoized values and recalculate them on next render.
Instance variables never forget. 🐘
If computing the initialInstance is costly, you may pass a function that returns an initialInstance.useInstance will only call the function on mount.
Not that creating two functions is expensive,
but we could re-write the example above using a lazy initializer, like this.
`js
// this is only called once, on mount, per component instance
const getInitialInstance = setCount => ({
increment: () => setCount(c => c + 1),
decrement: () => setCount(c => c - 1),
});
const useCounter = initialCount => {
const [count, setCount] = useState(initialCount);
const self = useInstance(getInitialInstance(setCount));
return {
count,
...self,
};
};
`
Notice that we moved getInitialInstance into a static fucntion _outside_ of useCounter.useCounter
This helps to reduce the complexity of .getInitialInstance
An added side effect is that is now highly testable.
You might even take this one step further and refactor your methods
into it's own cusom Hook. Isn't coding fun? 😊
`js
const getInitialInstance = setCount => ({
increment: () => setCount(c => c + 1),
decrement: () => setCount(c => c - 1),
});
const useCounterMethods = setCount =>
useInstance(getInitialInstance(setCount));
const useCounter = initialCount => {
const [count, setCount] = useState(initialCount);
const methods = useCounterMethods(setCount);
return {
count,
...methods,
};
};
``
You can view/edit the "you clicked" sample code above on CodeSandbox.

MIT Licensed
Thanks goes to these wonderful people (emoji key):
|
Donavon West
🤔 🚇") 🚧 👀 💻 🎨 |
| :---: |
This project follows the all-contributors specification. Contributions of any kind welcome!