Читаем исходный код – Chakra UI
Chakra UI – популярная UI библиотека для React. Она модульная и поддерживает кастомизацию компонентов.
Алекс Кондов изучил исходный код библиотеки и поделился интересными абстракциями, которые он нашел. Будет полезно изучить код тем, кто занимается разработкой UI библиотеки.
Пример создания контекста:
export const [ButtonGroupProvider, useButtonGroup] =
createContext<ButtonGroupContext>({
strict: false,
name: 'ButtonGroupContext',
})
export function createContext<T>(options: CreateContextOptions<T> = {}) {
// ...
const Context = createReactContext<T | undefined>(undefined)
// ...
function useContext() {
const context = useReactContext(Context)
if (!context && strict) {
const error = new Error(
errorMessage ?? getErrorMessage(hookName, providerName),
)
// ...
throw error
}
return context
}
return [Context.Provider, useContext, Context] as CreateContextReturn<T>
}
https://alexkondov.com/reading-code-chakra-ui/