Skip to content

Commit 670699e

Browse files
committed
Learning context
1 parent 30bdf7f commit 670699e

1 file changed

Lines changed: 23 additions & 17 deletions

File tree

  • epic-react-kent-c-dodds/03-Advanced-React-Hooks/src/exercise

epic-react-kent-c-dodds/03-Advanced-React-Hooks/src/exercise/03.js

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,42 @@
33

44
import * as React from 'react'
55

6-
// 🐨 create your CountContext here with React.createContext
6+
const CountContext = React.createContext()
77

8-
// 🐨 create a CountProvider component here that does this:
9-
// 🐨 get the count state and setCount updater with React.useState
10-
// 🐨 create a `value` array with count and setCount
11-
// 🐨 return your context provider with the value assigned to that array and forward all the other props
12-
// 💰 more specifically, we need the children prop forwarded to the context provider
8+
function useCountContext() {
9+
const context = React.useContext(CountContext)
10+
if (!context) {
11+
throw new Error('useCount must me used within the CountProvider.')
12+
}
13+
return context
14+
}
15+
16+
function CountProvider(props) {
17+
const [count, setCount] = React.useState(0)
18+
const value = [count, setCount]
19+
return <CountContext.Provider value={value} {...props} />
20+
}
1321

1422
function CountDisplay() {
15-
// 🐨 get the count from useContext with the CountContext
16-
const count = 0
23+
const [count] = useCountContext()
1724
return <div>{`The current count is ${count}`}</div>
1825
}
1926

2027
function Counter() {
21-
// 🐨 get the setCount from useContext with the CountContext
22-
const setCount = () => {}
23-
const increment = () => setCount(c => c + 1)
28+
const [, setCount] = useCountContext()
29+
const increment = () => {
30+
setCount(c => c + 1)
31+
}
2432
return <button onClick={increment}>Increment count</button>
2533
}
2634

2735
function App() {
2836
return (
2937
<div>
30-
{/*
31-
🐨 wrap these two components in the CountProvider so they can access
32-
the CountContext value
33-
*/}
34-
<CountDisplay />
35-
<Counter />
38+
<CountProvider>
39+
<CountDisplay />
40+
<Counter />
41+
</CountProvider>
3642
</div>
3743
)
3844
}

0 commit comments

Comments
 (0)