facebook

How to structure the data in redux store

How to structure the data in redux store
Average rating: 5
(1 votes)

Thanks! You’ve rated this material!

If you use redux, you could ask yourself this question many times. Thre are a bunch of approaches in practice with some tradeoffs between access time and ease of iteration. So, how to structure the data in redux store?

Let’s begin with basics. Some common approaches you already familiar with.

If each item in your data has an id, you can shape your store as an Object or as an Array of ObThe jects:

  1. The simplest option is

    Array of flat objects

    With it you can store your data in a particular order, but you can’t access a specific item by id or name without iterating and filtering.

  2. Option with fast access to each item

    Object keyed on id {id: {values}}

    But here you can not easily access the id of a given item while you’re iterating using Object.values()

  3. A mix of two options above

    Array of objects

    It lets you iterate over an ordered list and access the id and the values at the same time, but it doesn’t give you fast O(1) access since it’s an array at heart and you need to filter it to extract a row by id.

And here comes the alternative approaches to structure your data.

  1. Structure your data in redux store like a

    database of rows indexed by id

    This option benefits of both easy iteration with Object.values(state.categories), and fast O(1) access to individual items. id is the key for the raw and at the same time a property in the raw itself. This duplication gives us a flexibility at access.
    How to structure th data in redux store. Syndicode
    If we access store data using different keys besides id, we can build as many indexes as we want for the same data, which gives us O(1) access based on any column, just like we would have in a database. Your indexes can also be pure functions of the data instead of static objects if you need to keep them up-to-date when your store changes.

  2. If we send the data from our backend with an order key specifying each row’s position, we will

    make an index for order

    How to structure th data in redux store. Syndicode
    Now we can access a specific category instantly by its order, or use map, filter, and reduce on the whole list. With this approach we can add or remove items to our categories store in the frontend, and always still be able to get the ordered list.

More examples and further reading options are available here.

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

*By submitting this form you agree with our Privacy Policy.

Mailing & Legal Address

Syndicode Inc. 340 S Lemon Ave #3299, Walnut CA, 91789, USA

Visiting & Headquarters address
Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
Email info@syndicode.com
Phone (+1) 9035021111