Since hooks was introduced in React, React means functional programming. But sometimes a "service"-like object is needed to solve some features. I.e.:
function MyComponente() {
const cache = useCache({ name: "my-component" });
console.log(cache.getSelectedItem());
console.log(cache.setSelectedItem(5));
// ....
return <Items cache={cache} />;
}
In the above code the "service"-like object is the cache
. Here the cache
instance is created with a "hook"-approach. The code could look like the following:
import { cacheRegister, defaultFilters } from "../reactive-vars";
const useCache = ({name}) => {
const initialState = cacheRegister[name]();
const currentState = cacheRegister[name];
return useRef({
getName: () => name,
getSelectedItem: () => cacheRegister[name].selectedItem,
setSelectedItem: (item) => cacheRegister[name]({ ...cacheRegister[name], selectedItem: item }),
// ....
});
}
Is this the best approach? The useRef
avoids the recreation of the cache-instance and keeps the reference of cache stable.
I would go with useRef
definitely. That is the way I am utilizing services on my React projects. As you mentioned, ref is a stable wrapper, and since services should be one-time instantiated and not depending on some outer state, then useRef makes it perfect to use. I just like to define services with JS classes, and then to use it with something like: const service = useRef(new SomeService(...someParams))
;