All Downloads are FREE. Search and download functionalities are using the official Maven repository.

utils.createExtendedContext.tsx Maven / Gradle / Ivy

The newest version!
import React, {
    createContext,
    Context,
    useContext,
    ReactNode,
    useMemo,
} from 'react'

/**
 * Создание "расширяесого" контекста, который объеденяет значение родительского с текущим
 */
export function createExtendedContext | unknown[]>(
    defaultValue: T,
    mergeFn: (parent: T, current: T) => T,
): Context {
    const ReactContext = createContext(defaultValue)

    function Provider({ value, children }: { value: T, children?: ReactNode | undefined; }) {
        const parentValue = useContext(ReactContext)
        const mergedValue = useMemo(() => mergeFn(parentValue, value), [parentValue, value])

        return (
            
                {children}
            
        )
    }

    Object.assign(Provider, ReactContext.Provider)

    return new Proxy(ReactContext, {
        get(target: typeof ReactContext, key: keyof typeof ReactContext) {
            if (key === 'Provider') {
                return Provider
            }

            return target[key]
        },
    })
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy