Created
June 1, 2020 09:30
-
-
Save Odonno/c475362158223ea38101f41d556dc4aa to your computer and use it in GitHub Desktop.
State management comparison - pure React hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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