useContext + useReducer with Sample Code
Tags: javascript, react, beginners
Published: 2023-12-11 04:51:32

In the previous blog posts, I discussed the functionalities of useContext and useReducer. Briefly, useContext is a React Hook that enables us to access Context or data from any components within a nested tree. useReducer is a state management hook that handles multiple states depending on the passed action types.

In today's article, I will demonstrate how we can effectively maintain large-scale applications by leveraging both useContext and useReducer.

This is a simple book list app where users can add books to read. The app displays the total number of books on the list and indicates the next book to read. It's designed as a demonstration app, intentionally kept as simple as possible without including fancy functions or even CSS.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xzxh81fecl6gps7wsw4h.jpeg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8boqv5oa7o2vdvqnizdk.jpeg)


First, let's start with only two components, `<Books /> `and `<BookList />`, using **only the useReducer hook**.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjdcri8emzwpqk8d7ym2.jpeg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kcovkc94sqh7p617we52.jpeg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1udz8sd1edr0cpe6j46b.jpeg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ayjmiag4f6djl30yusb9.jpeg)

This setup works seamlessly, as demonstrated in the images. When users enter the title of a book (e.g., "book1," "book2," "book3," and "book4") and click the delete button (e.g., deleting "book1"), the app accurately reflects the updated count (3 books) and displays the first book in the list ("book2") as the next one to read.

Now, what if we want to add a book detail page nested within the `<BookList />` component? We would need to pass down `books={books}` and `dispatch={dispatch}` to that component to access the data. However, prop-drilling will occur and make data management challenging.

What if we want to create a separate component for the top part, including "Books to Read," "Number of books in my list," and "Next book to read" where the "books" data is required for display?

Here's the solution: Using useContext.
Let's examine this step by step.

**BookContext.js**
We create BookContext using createContext.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jf8tl7e592nsluwp3wc2.jpeg)

**BookProvider.jsx**
In this component, we define a reducer so that we can successfully pass the action types via the Provider using `value={}`.
Here, `initialState`, `reducer`, and `useReducer` all come from the `<Books /> `component.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8drnhk2039m9pl5xfdtx.jpeg)

**App.js**
To use the context, we wrap `<Header />` and `<Books />` with the provider we created. Now, we have access to the `books` and `dispatch`.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h67zewp402qsx90ru2kq.jpeg)

**Header.jsx**
We have a custom hook, `useBookContext`, to access the needed data. On this page, we only need access to `book`.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1se29rt4m1ymh9g7abe.jpeg)

**BookList.jsx**
Here, we use `useBookContext` to access both `book` and `dispatch`.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pe8cea8plp3fdfp8qwtx.jpeg)

**Books.jsx**
Now, the code is simplified and easy to read.
There's no need to pass `book={book}` and `dispatch={dispatch}` explicitly.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8c2yp64rkxxo9ii8p7bx.jpeg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gq58cxly602u0yt5www5.jpeg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/203lkr14fy291ga71moc.jpeg)

The action types in the reducer precisely define the actions to take, ensuring the maintenance of an immutable state. useContext makes it easy for components to access only the necessary data without the need to pass it all the way down to child components. This combination of useContext and useReducer contributes to making large-scale applications more readable, manageable, and dynamic!

Some developers choose to create separate files exclusively for a reducer, as well as for a Context and Provider. I'll delve deeper into this approach to explore its benefits further. So many areas can be enhanced, such as using capital letters for action type constants, adding more features and styles, and implementing input field validations. These aspects could become my next project as I continue to refine and expand this undertaking.

I've noticed that some developers engage in debates over "useContext + useReducer vs Redux." Now, I'm excited to learn more about Redux.

**Update:**
I elevated the project by incorporating TypeScript, enhancing the application's type safety and robustness.

Home
The Home page presents the user's book list, displayed at the bottom. A card at the top showcases the total number of books in the list. Additionally, a recommended book, which is the first in the list, is featured at the top. The integration of useContext and useReducer enhances state management.

Add/Edit
This section empowers users to create new books or edit existing ones. When editing, the form displays the existing data for seamless modification.

Show
In this section, users gain access to detailed information about a specific book from their list.

Edit Tags
The Edit Tags page leverages the power of react-select to simplify the selection, creation, editing, and deletion of tags. This library provides an intuitive interface for managing multiple tags associated with books.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/280gz18xhr8wxg50bl9i.jpeg)