Refactoring user components

First, we refactor the user components, and then we move on to the post components.

Let's refactor the user-related components now:

  1. 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>
)
}
}
  1. 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'
  1. 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
  1. Again, we import useContext and StateContext in src/user/Login.js:
import React, { useState, useContext } from 'react'
import { StateContext } from '../contexts'
  1. Then, we remove the dispatch prop, and use the Context Hook instead:
export default function Login () {
const { dispatch } = useContext(StateContext)
  1. 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)
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.165.246