Building our own custom useReducer Hook

·

2 min read

useReducer is a local state management hook just like useState to store and update the state of a component. useReducer will take a reducer function and initial state as its two parameters. Let's learn how to build our custom useReducer hook. I will call the custom useReducer hook as useMyReducer.

Let's build a Todo app using our custom useReducer hook. I will divide my Todo app into 3 components.

  1. The parent component which will store all the todos.

  2. The component containing an input field and add button.

  3. The component that will return us each todo in the form of a card.

Now let's begin creating our custom useReducer hook.

  1. Basically, useReducer hook will take two parameters one is reducer function and initialState which can be anything like an array, object, string, or number, etc and it will return us an array with state and dispatch function.

  2. useReducer hook will maintain an internal local state which by default will store the initialState which was received as a parameter. let's use useState to maintain this local state which will be used by the reducer function (as a parameter).

  3. Now let's work on the dispatch function. The dispatch function will take action parameters which contains the action type and action payload so let's call it "actionParameters".

  4. The dispatch function will call the reducer function with state and actionParameters as the arguments. The reducer will in turn return the updated state after going through all the provided logic and conditions.

  5. This updated state will be set as the new state (local state of custom useReducer hook) which will be used by the reducer function for further operations. Now our custom useReducer hook is ready to be used.