Skip to content

Instantly share code, notes, and snippets.

@abiriadev
Created April 20, 2024 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abiriadev/59904587e3a5964a519fd53f8d5e1706 to your computer and use it in GitHub Desktop.
Save abiriadev/59904587e3a5964a519fd53f8d5e1706 to your computer and use it in GitHub Desktop.
import {
PropsWithChildren,
createContext,
useState,
} from 'react'
export const FormFactory = <T,>(init: T) => {
const Context = createContext<{
value: T
setValue: <K extends keyof T>(
key: K,
value: T[K],
) => void
}>({ value: init, setValue: () => {} })
const Form = ({ children }: PropsWithChildren) => {
const [state, setState] = useState(init)
return (
<Context.Provider
value={{
value: init,
setValue: (key, value) =>
setState({
...state,
[key]: value,
}),
}}
>
{children}
</Context.Provider>
)
}
return [Form, Context] as const
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment