I have seen a pattern from the react-query library which does the following:
(OOP)
// it instantiates an object from a class
const queryClient = new QueryClient()
(Hooks)
// Then it passes this object as a prop to the provider
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
and in the <Todos /> component, this library gives you the option to both use the client or use a hook.
// Todos
const client = useQueryClient(); // (Hook)
const query = useQuery( key, fn, option ); // (Hook)
What I cannot understand is how this library is able to keep its state in sync between a normal javascript class object namely the client and the usage of other hooks. What I mean by that is for example, you are able to use the hook useQuery with a key as the first argument and what this hook does is that executes the fn function and stores the result in a data property inside the query.
The funny part is that you can then use this data by calling the following method from the client.
const { data } = client.getState(key);
So what it actually does behind the scenes in order to keep in sync both a classic javascript object and hooks ?
const client = useQueryClient(); // (Hook)
const query = useQuery( key, fn, option ); // (Hook)
// ----> in sync : query.data === client.getState(key).data