Перейти к содержанию

useContext

useContext

1
function useContext<T>(context: Context<T>): T;

Used to grab context within a context provider scope to allow for deep passing of props without having to pass them through each Component function.

1
const [state, { increment, decrement }] = useContext(CounterContext);

It is often a good idea to wrap useContext in a function like so:

1
2
3
4
5
6
7
function useCounterContext() {
    const context = useContext(CounterContext);
    if (!context) {
        throw new Error("useCounterContext: cannot find a CounterContext")
    }
    return context;
}

See the API reference of createContext for the explanation of what this solves.

Комментарии