Skip to content

Instantly share code, notes, and snippets.

@tqwewe
Created May 6, 2020 07:19
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 tqwewe/312b1e137690f276910fb35d76631fb1 to your computer and use it in GitHub Desktop.
Save tqwewe/312b1e137690f276910fb35d76631fb1 to your computer and use it in GitHub Desktop.
React hooks and context with create-store util
// src/App.jsx
import React from 'react'
import { Provider as CountProvider } from './context/count'
import ShowCount from './components/ShowCount'
const App = () => {
return (
<CountProvider>
<ShowCount />
</CountProvider>
)
}
export default App
// src/context/count.js
import { useState } from 'react'
import createStore from '../utils/create-store'
const useCount = () => {
const [count, setCount] = useState(0)
const inc = () => setCount(count + 1)
const dec = () => setCount(count - 1)
return {
count,
inc,
dec,
}
}
export const { ctx, Provider } = createStore(useCount)
// src/utils/create-store.jsx
import React, { createContext } from 'react'
const createStore = (useHook) => {
const ctx = createContext()
const Provider = ({ children }) => {
const value = useHook()
return <ctx.Provider value={value}>{children}</ctx.Provider>
}
return {
ctx,
Provider,
}
}
export default createStore
// src/components/ShowCount.jsx
import React, { useContext } from 'react'
import { ctx as CountContext } from '../context/count'
const ShowCount = () => {
const { count, inc, dec } = useContext(CountContext)
return (
<div>
Count: {count}
<button onClick={() => inc()}>Increment</button>
<button onClick={() => dec()}>Decrement</button>
</div>
)
}
export default ShowCount
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment