Skip to content

Instantly share code, notes, and snippets.

@Odonno
Created June 1, 2020 09:30
Show Gist options
  • Save Odonno/c475362158223ea38101f41d556dc4aa to your computer and use it in GitHub Desktop.
Save Odonno/c475362158223ea38101f41d556dc4aa to your computer and use it in GitHub Desktop.
State management comparison - pure React hooks
export type StoreContextState = {
todos: Todo[];
loadTodos: () => Promise<void>;
createTodo: (content: string) => Promise<void>;
changeContent: (todo: Todo, content: string) => void;
updateTodo: (id: number, content: string) => Promise<void>;
deleteTodo: (id: number) => Promise<void>;
};
const StoreContext = createContext<StoreContextState>({} as StoreContextState);
type StoreContextProviderProps = {
children?: ReactNode;
};
export const StoreProvider = ({ children }: StoreContextProviderProps) => {
const [todos, setTodos] = useState<Todo[]>([]);
const loadTodos = useCallback(
async () => {
const response = await fetch(`${apiUrl}/todos`);
const results = await response.json();
return setTodos(results);
},
[setTodos]
);
// ... other mutations
const state = {
todos,
loadTodos,
...
};
return (
<StoreContext.Provider value={state}>
{children}
</StoreContext.Provider>
);
};
export const useStore = () => useContext(StoreContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment