Creating the StateContextWrapper

For the other Hooks, which make use of the StateContext, we have to define another wrapper to provide the StateContext to the Hooks.

Let's now define the StateContextWrapper component with the following steps:

  1. Edit src/hooks/testUtils.js and adjust the import statements to import the useReducer Hook, the StateContext, and the appReducer function:
import React, { useReducer } from 'react'
import { StateContext, ThemeContext } from '../contexts'
import appReducer from '../reducers'
  1. Define a new function component called StateContextWrapper. Here we are going to use the useReducer Hook to define the app state, which is similar to what we did in the src/App.js file:
export function StateContextWrapper ({ children }) {
const [ state, dispatch ] = useReducer(appReducer, { user: '', posts: [], error: '' })
  1. Next, define and return the StateContext.Provider, which is similar to what we did for the ThemeContextWrapper:
    return (
<StateContext.Provider value={{ state, dispatch }}>
{children}
</StateContext.Provider>
)
}

As we can see, creating a context wrapper always works similarly. However, this time, we are also defining a Reducer Hook in our wrapper component.

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

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