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.