Skip to content

Instantly share code, notes, and snippets.

@binhtran04
Last active April 3, 2020 14:28
Show Gist options
  • Save binhtran04/fec6ba2a280b0b56ce34913e1ead2191 to your computer and use it in GitHub Desktop.
Save binhtran04/fec6ba2a280b0b56ce34913e1ead2191 to your computer and use it in GitHub Desktop.
Skeleton for MovieContext
/**
initialMovies = [
{
id: uuidv4(),
title: 'The Godfather',
year: 1972,
watched: false,
},
{
id: uuidv4(),
title: 'Inception',
year: 2010,
watched: false,
},
...
]
*/
import { initialMovies } from './initialState';
// Create a context with by calling React.createContext()
const MoviesContext = React.createContext();
// initial reducer
const moviesReducer = (state, action) => {
return state;
};
/**
state can contain more such as a loading status, and error state. e.g.
{
status: 'loading',
movies: [],
error: null,
}
*/
const initialState = {
movies: initialMovies,
};
// Create a custom MoviesProvider for the context
export const MoviesProvider = props => {
const [state, dispatch] = React.useReducer(moviesReducer, initialState);
// useMemo to optimize the context value
const value = React.useMemo(() => ({ state, dispatch }), [state]);
return <MoviesContext.Provider value={value} {...props} />;
};
// Custom hook useMoviesContext
export const useMoviesContext = () => {
const context = React.useContext(MoviesContext);
if (!context) {
throw new Error('useMoviesContext must be used inside a MoviesProvider');
}
const { state, dispatch } = context;
const { movies } = state;
return { movies };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment