Skip to content

Instantly share code, notes, and snippets.

@jeandenis-k
Last active April 17, 2020 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeandenis-k/c0bd610fe451ab2848085e09ea9f939c to your computer and use it in GitHub Desktop.
Save jeandenis-k/c0bd610fe451ab2848085e09ea9f939c to your computer and use it in GitHub Desktop.
How to pass dispatch with context to child components
// Une valeur globale de contexte permet de passer à un composant enfant une valeur
// définie dans un composant plus haut, sans avoir à passer par toutes les props des
// composants intermédiaires
export const CreationDispatch = React.createContext<Dispatch<CreationAction>>(
null!
);
// Dans le composant parent, on instancie dispatch et on le passe dans
// dans la valeur de contexte
function parentComponent() {
const [creationState, dispatch] = useReducer(reducer, initialCreationState);
return (
<DispatchContext.Provider value={dispatch}>
//...
<Import ... >
//...
</DispatchContext.Provider>
);
}
// Dans le composant enfant, on récupère dispatch dans la valeur globale de contexte
function Import() {
const dispatch = useContext(CreationDispatch);
//...
dispatch({ type: "loadDesign", design });
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment