Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matthewdordal/1cb3db6dc1947880a8743e13d5915b89 to your computer and use it in GitHub Desktop.
Save matthewdordal/1cb3db6dc1947880a8743e13d5915b89 to your computer and use it in GitHub Desktop.
TypesScript custom useReducer hook example
import React from "react";
const setOpen = (open: boolean) =>
({
type: "SET_OPEN",
payload: { open }
} as const);
const setTitle = (title: string) =>
({
type: "SET_TITLE",
payload: { title }
} as const);
type Action = ReturnType<typeof setOpen | typeof setTitle>;
const defaultState = {
open: false,
title: ""
};
type State = typeof defaultState;
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "SET_OPEN": {
const { payload } = action;
return {
...state,
open: payload.open
};
}
case "SET_TITLE": {
const { payload } = action;
return {
...state,
title: payload.title
};
}
default:
return state;
}
};
const useCustomReducer = (inititalState: State) => {
const [state, dispatch] = React.useReducer(reducer, inititalState);
return [state, dispatch];
};
import React from "react";
const SET_OPEN: string = "SET_OPEN";
const SET_TITLE: string = "SET_TITLE";
interface SetOpenAction {
readonly type: typeof SET_OPEN;
payload: {
open: boolean;
};
}
interface SetTitleAction {
readonly type: typeof SET_TITLE;
payload: {
title: string;
};
}
type Action = SetOpenAction | SetTitleAction;
const setOpen = (open: boolean): SetOpenAction => ({
type: SET_OPEN,
payload: { open }
});
const setTitle = (title: string): SetTitleAction => ({
type: SET_TITLE,
payload: { title }
});
interface State {
open: boolean;
title: string;
}
const defaultState: State = {
open: false,
title: ''
}
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case SET_OPEN: {
const { payload } = action as SetOpenAction;
return {
...state,
open: payload.open
};
}
case SET_TITLE: {
const { payload } = action as SetTitleAction
return {
...state,
title: payload.title
}
}
default:
return state;
}
};
const useCustomReducer = (inititalState: State) => {
const [state, dispatch] = React.useReducer(reducer, inititalState)
return [state, dispatch]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment