Programming

Higher-Order React Hooks

As part of the next step in learning React, I’ve been moving the business logic for one of the components I made early on into a custom hook. The component I’m refactoring displays a table, along with controls for pagination and filtering. I moved the logic for sending the request to the custom hook, along with some of the state required for making the request. Now, the component receives the row and status of the row retrieval request through the custom hook. This also allows the same data to be used in other components (like pie charts).

Another component in the table component allowed users to export all rows in the table as a CSV file. Since the table normally only retrieves the rows for the active page in the table, a separate request is used to generate the CSV file. It does inherit the same active filters and sort options as the table, however. The problem is, the table component doesn’t have all of the required data in it’s state for making the export request – the custom hook only exposes the state required for interface display.

What I did to solve the issue is move the export logic into it’s own hook, which takes the data required to send the export request as it’s parameters. The export hook is then called as a higher order function in the table custom hook, which exposes it to the table component as one of it’s return values.

TypeScript

This means the custom table hook “injects” the active filter data (and other values), returning a simplified hook with actions the display component can easily call. Finally, the table export component takes the hook function as one of it’s props.

Recent Posts

Finding and Fixing Layout Shifts/CLS Issues

Over the past few months, I've been working on fixing Cumulative Layout Shift issues for…

2 years ago

web-vitals vs Lighthouse vs PageSpeed Insights – What’s the Difference?

There are quite a few different libraries out there that can help with measuring your…

2 years ago

Google Search Console Showing High CLS But PageSpeed Insights Shows Good Score

So you've asked a plugin provider/your theme designer/ads provider to fix CLS issues that you…

2 years ago

Using AMP Pages to Boost your Mobile Performance

Site Speed Having a slow site can be a real headache, and unlike many issues…

3 years ago

How to get the intrinsic coordinates on an image mouse click

I'm currently working on a program that can generate a customizable image report. It needs…

3 years ago

Score Doesn’t Matter – How to Sanity-Check Your GTMetrix Report

I commonly see people running a site speed test through GTMetrix or Google PageSpeed Insights…

3 years ago