First, we refactor the user components, and then we move on to the post components.
Let's refactor the user-related components now:
- Edit src/user/UserBar.js, and also remove the props there (code marked in bold should be removed), since we do not need to manually pass them down anymore:
export default function UserBar ({ user, dispatch }) {
if (user) {
return <Logout user={user} dispatch={dispatch} />
} else {
return (
<React.Fragment>
<Login dispatch={dispatch} />
<Register dispatch={dispatch} />
</React.Fragment>
)
}
}
- Then, we import the useContext Hook and the StateContext in src/user/UserBar.js, in order to be able to tell whether the user is logged in or not:
import React, { useContext } from 'react'
import { StateContext } from '../contexts'
- Now, we can use the Context Hook to get the user state from our state object:
export default function UserBar () {
const { state } = useContext(StateContext)
const { user } = state
- Again, we import useContext and StateContext in src/user/Login.js:
import React, { useState, useContext } from 'react'
import { StateContext } from '../contexts'
- Then, we remove the dispatch prop, and use the Context Hook instead:
export default function Login () {
const { dispatch } = useContext(StateContext)
- We repeat the same process in the src/user/Register.js component:
import React, { useState, useContext } from 'react'
import { StateContext } from '../contexts'
export default function Register () {
const { dispatch } = useContext(StateContext)
- In the src/user/Logout.js component, we do the same, but also get the user state from the state object:
import React, { useContext } from 'react'
import { StateContext } from '../contexts'
export default function Logout () {
const { state, dispatch } = useContext(StateContext)
const { user } = state
Our user-related components now use a context instead of props. Let's move on to refactoring the post-related components.