Skip to main content
Version: v0.x (deprecated)

createGenericContext

This version is deprecated

This documentation is for use-less-react v0.x, which has been deprecated.
See v1.0 documentation for the current API.

Generic utility that simplifies the creation of React contexts with full TypeScript type safety.


Overview

createGenericContext provides both a Provider component and a corresponding hook that ensures the context is only accessed within its own provider.


Example

import { createGenericContext } from '@dxbox/use-less-react/client';
import { useReactiveInstance } from '@dxbox/use-less-react/client';

const [UserProvider, useUser] = createGenericContext<{ user: User }>();

function App() {
const userRef = useRef(new User());

return (
<UserProvider value={userRef.current}>
<Profile />
</UserProvider>
);
}

function Profile() {
const userInstance = useUser();

const { state: user } = useReactiveInstance(
userInstance,
(instance) => ({
name: instance.name,
age: instance.age,
}),
['name', 'age'],
);

return <div>{user.name} is {user.age} years old</div>;
}

Usage with Objects and Arrays

When sharing objects or arrays, use useMemo to avoid changing references at every render:

const [LogConfigProvider, useLogConfig] = createGenericContext<{ enableLog: boolean }>();

function App() {
const logConfig = useMemo(() => ({
enableLog: true,
otherValue: 'value',
}), []);

return (
<LogConfigProvider value={logConfig}>
{/* ... */}
</LogConfigProvider>
);
}

Return value

PropertyTypeDescription
GenericContextProviderFC<PropsWithChildren<{ value: T }>>A provider component that exposes the context value.
useGenericContext()() => THook to access the context value. Throws an error if called outside of its provider.

Notes

  • The value passed to the provider should be stored inside a useRef if the reference should remain stable across renders.
  • The hook enforces safety by throwing an error if called outside of its context provider.

Next: See createHydrationContext for SSR hydration.

Migration: See v1.0 createGenericContext for the modern equivalent.