filename:
src/contexts/SomeContext.tsx
branch:
main
back to repo
import React, { createContext, useContext, ReactNode } from 'react';
// this is just a template for how to possibly setup a context
// this is the context object interface, we will use this to define the data passed in the context
interface SomeContextObject {
somevalue;
someothervlaue;
somefunction;
}
const SomeContext = createContext<SomeContextObject | undefined>(undefined);
function samplecontextfunction() {
// nice thing about interfaces is we can also provide access to functions
// this function can do anything such as updating context
return 0;
}
// use the provider to pass "value" to users of the context
export function SomeProvider({ children }: { children: ReactNode }) {
const value: SomeContextObject = {
// value uses the earlier definition of SomeContextObject to decide its members
somevalue: 0,
someothervlaue: 1,
somefunction: samplecontextfunction
};
return (
<SomeContext.Provider value={value}>
{children}
</SomeContext.Provider>
);
}
// calling this function elsewhere in the project will now check that the context is avalible and if so return it
export function useSomeContext() {
const context = useContext(SomeContext);
if (context === undefined) {
throw new Error('use context outside context provider');
}
return context;
}