Skip to content
Advertisement

Adding object values to useMemo hook for React

I am attempting to create a react-table component using data that is pulled from a database. From the documentation I have read (https://react-table.tanstack.com/docs/quick-start), it seems like the react-table library uses a useMemo hook to create the data which will be displayed on the table. However, I am having trouble actually adding data to the useMemo hook, since I am not familiar with it.

I have a simple JS object that holds the counts of instances of each category of outages that occur in our database. Once I have the counts, I attempt to pass it to my instance of useMemo, however properties of undefined ‘streamCount’ is returned. I think I am passing the object to useMemo incorrectly. Any help is appreciated.

JavaScript

Advertisement

Answer

The useMemo hook’s callback function doesn’t take any arguments, it simply takes a callback function that returns a value you want, or need, to memoize, the dependency array lists external references that the memoized value depends on.

useMemo

JavaScript

Returns a memoized value.

Pass a “create” function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

Move the logic for computing the counts into the useMemo callback and use data (the props value) as the dependency. You can simplify/reduce the code to be more DRY by abstracting the common pattern of mapping the service_type to one of the counts keys and then mapping back but just using the service_type as the counts keys. With this change you can simply use dynamic object properties to update the counts for each outage type. When the counts have been computed create an array of key-value pairs from the object and map this to the array of objects with type and count keys.

JavaScript

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement