Created
May 6, 2020 07:19
-
-
Save tqwewe/312b1e137690f276910fb35d76631fb1 to your computer and use it in GitHub Desktop.
React hooks and context with create-store util
This file contains 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
// 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 |
This file contains 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
// 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) |
This file contains 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
// 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 |
This file contains 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
// 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