Defining the Reducer Hook

After defining the actions and the reducer function, we are going to define the Reducer Hook, and pass its state and the dispatch function to the components that need it.

Let's start implementing the Reducer Hook:

  1. First, we have to import the useReducer Hook, by adjusting the following import statement in src/App.js:
import React, { useState, useReducer } from 'react'
  1. Edit src/App.js, and remove the following State Hook:
    const [ user, setUser ] = useState('')

Replace the preceding State Hook with a Reducer Hook—the initial state is an empty string, as we had it before:

    const [ user, dispatchUser ] = useReducer(userReducer, '')
  1. Now, pass the user state and the dispatchUser function to the UserBar component, as a dispatch prop:
            <UserBar user={user} dispatch={dispatchUser} />
  1. We do not need to modify the CreatePost component, as we are only passing the user state to it, and that part did not change.
  2. Next, we edit the UserBar component in src/user/UserBar.js, and replace the setUser prop with the dispatch function:
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. Now, we can edit the Login component in src/user/Login.js, and replace the setUser function with the dispatch function:
export default function Login ({ dispatch }) {
  1. Then, we replace the call to setUser with a call to the dispatch function, dispatching a LOGIN action:
            <form onSubmit={e => { e.preventDefault(); dispatch({ type: 'LOGIN', username }) }}>
We could also make functions that return actions—so-called action creators. Instead of manually creating the action object every time, we could simply call loginAction('username') instead, which returns the corresponding LOGIN action object.
  1. We repeat the same process for the Register component in src/user/Register.js:
export default function Register ({ dispatch }) {
// ...
<form onSubmit={e => { e.preventDefault(); dispatch({ type: 'REGISTER', username }) }}>
  1. Finally, we also repeat the same process for the Logout component in src/user/Logout.js:
export default function Logout ({ user, dispatch }) {
// ...
<form onSubmit={e => { e.preventDefault(); dispatch({ type: 'LOGOUT' }) }}>

Now, our app should work the same way as before, but it uses the Reducer Hook instead of a simple State Hook!

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

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