feat: context factory

This commit is contained in:
2025-08-26 16:11:40 +04:00
parent 5b5c2fe230
commit 31bd888357
7 changed files with 71 additions and 185 deletions

View File

@ -0,0 +1,31 @@
"use client";
import React, { createContext, FC, PropsWithChildren, useContext } from "react";
export default function makeContext<State, HookArgs = {}>(
useValue: (args: HookArgs) => State,
displayName?: string
) {
const Context = createContext<State | undefined>(undefined);
Context.displayName = displayName ?? "Custom";
const Provider: FC<PropsWithChildren<HookArgs>> = ({
children,
...hookArgs
}) => {
const value = useValue(hookArgs as HookArgs);
return <Context.Provider value={value}>{children}</Context.Provider>;
};
const useContextHook = () => {
const context = useContext(Context);
if (!context) {
throw new Error(
`${Context.displayName}Context must be used within ${Context.displayName}ContextProvider`
);
}
return context;
};
return [Provider, useContextHook] as const;
}