Skip to content

Instantly share code, notes, and snippets.

@danielkcz
Last active October 15, 2020 05:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielkcz/1d3a62d6831aaedf5f34b12d9b2f287d to your computer and use it in GitHub Desktop.
Save danielkcz/1d3a62d6831aaedf5f34b12d9b2f287d to your computer and use it in GitHub Desktop.
useQuery + useContext
import { useQuery } from 'react-apollo-hooks'
const RandomGiphy = () => {
const { tag } = useSettings()
const { data } = useQuery(
RandomGiphyQuery, {
variables: { tag }
}
}
// handle loading & error states...
return <img src={data.giphy.random.url} />
}
import React from 'react'
const context = React.createContext()
export const SettingsProvider = ({ children }) => {
// useReducer could be better candidate for a more complex scenarios
const [settings, updateSettings] = React.useState({ tag: 'kittens' })
return (
<context.Provider value={{ data: settings, update: updateSettings }}>
{children}
</context.Provider>
)
}
// hook to consume data only
export const useSettings = () => {
return React.useContext(context).data
}
// hook to get update callback (or dispatch)
export const useSettingsUpdate = () => {
return React.useContext(context).update
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment