Way of the Script — React Typescript & Context API Patterns

Ref: https://i.ytimg.com/vi/NRHYxYpHWo4/maxresdefault.jpg

Basic Example

import React, {Component, createContext} from "react";
const ctxt = createContext<any>(null);
export interface ICtx {
state: IState;
actions: IActions;
}
interface IState {
count: number
}
interface IAction {
increase: () => void;
decrease: () => void;
}
class AppProvider extends Component<{}, IState> {
state: IState = {
count: 0
};
increase = () => this.setState({count: this.state.count + 1});
decrease = () => this.setState({count: this.state.count - 1});
render() {
return (
<ctxt.Provider
value={{
state: this.state,
actions: {
increase: this.increase,
decrease: this.decrease
}
}}>
{this.props.children}
</ctxt.Provider>
);
}
}
export {AppProvider};
export const AppConsumer = ctxt.Consumer;
class InitialExample extends Component {
render() {
return (
<AppProvider>
<CounterComponent />
</AppProvider>
);
}
}
import { AppConsumer, ICtx } from "./app-ctx";const CounterComponent = () => {
return (
<AppConsumer>
{(ctx: ICtx) => {
return (
<div>
{ctx.state.count}
<button onClick={ctx.actions.increase}>Increase</button
<button onClick={ctx.actions.decrease}>Decrease</button
</div>
);
}}
</AppConsumer>
);
};
Context state is now typed :>
Actions to update state are also typed :>

Lets Get Hooked

const ctxt = createContext<any>(null);
export const ctxt = createContext<any>(null);
import React, { useContext } from "react";                       import { ICtx, ctxt } from "./app-ctx";                                               const CounterComponent = () => {                         
const ctx: ICtx = useContext(ctxt);
return (
<div>
{ctx.state.count}
<button onClick={ctx.actions.increase}>Increase</button>
<button onClick={ctx.actions.decrease}>Decrease</button>
</div>
);
};
export default CounterComponent;

Tis the end of our quest!

Ref: http://www.hdfondos.eu/pictures/2013/1108/1/hammer-thor-picture-wallpaper-7241.jpg

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store