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.
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.