useReducer()

For more complicated components / modules, React now has redux-like functionality out of the box.

import React, { useReducer } from 'react'; export default function Filter(props) {

var [state, dispatch] = useReducer(reducer, initialState); function onChange(ev) {

dispatch({ type: "change", searchTerm: ev.target.value })

} return <input onChange={onChange} value={state.searchTerm}/>

} export const initialState = {

searchTerm: ""

}; export function reducer(state, action) {

switch(action.type) {

case: "change":

return { ...state, searchTerm: action.searchTerm };

default:

return state;

}

}

You may be trying to compare this to redux by finding those trusty mapState and mapDispatch functions. This is where things get interesting, especially when it comes to those async actions creators you may be used to with redux thunk. While React doesn’t come equipped with any middleware functionality or async action creators, it turns out that you can achieve this with zero additional libraries or framework code. How you achieve this however, can either make or break the utility of your static analysis tools like your compiler, eslint, etc.

Currently, in the above example, the onChange inner function is a dispatcher (technically it’s a handler as well), and effectively this is where your redux mapDispatch function exists, as it has a binding to the above dispatch function returned from useReducer. This gives us the necessary static analysis when we pass it into the JSX. As your application grows larger however, you may want to separate these out of your component render function, especially for those async action creators that contain more complex logic.