The Reducer Hook

Now that we have defined actions and the reducer function, we can create a Reducer Hook from the reducer. The signature for the useReducer Hook is as follows:

const [ state, dispatch ] = useReducer(reducer, initialState)

The only thing that we still need to define is the initialState; then we can define a Reducer Hook:

const initialState = { all: true }

Now, we can access the state by using the state object that was returned from the Reducer Hook, and dispatch actions via the dispatch function, as follows:

dispatch({ type: 'TOGGLE_EXPAND' })

If we want to add additional options to the action, we simply add them to the action object:

dispatch({ type: 'CHANGE_FILTER', fromDate: '2019-04-30' })

As we can see, dealing with state changes using actions and reducers is much easier than having to adjust the state object directly.

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

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