I’m building a custom Airtable block app that pulls data from several tables. The app shows this info in context and connected. I’m using useRecords hooks to keep things updated when users make changes. But now the app is super slow to load. It keeps restarting with each useRecords hook. Is there a trick to fix this while still getting all the table data I need?
Here’s a simplified version of what I’m doing:
import { useBase, useRecords } from '@airtable/blocks/ui';
import React from 'react';
function MyCustomApp() {
const base = useBase();
const tableNames = ['Products', 'Expenses', 'Clients', 'Sales', 'Team'];
const tables = React.useMemo(() => {
return tableNames.reduce((acc, name) => {
acc[name.toLowerCase()] = base.getTableByNameIfExists(name);
return acc;
}, {});
}, [base]);
console.log('Connected to tables');
const data = {};
for (const [key, table] of Object.entries(tables)) {
data[key] = useRecords(table);
console.log(`Loaded ${key} data`);
}
// Rest of the app logic
}
The console shows it’s restarting for each table. Any ideas on how to make this more efficient?
I’ve encountered this issue before in my Airtable projects. The problem lies in how React handles multiple state updates. A more efficient approach is to use a single useRecords call with a query that joins the necessary tables. This reduces the number of hooks and prevents excessive re-renders.
Here’s a rough example of how you might restructure your code:
I feel your pain, Tom. I’ve been there with complex Airtable apps. One approach that worked wonders for me was using a reducer pattern with useReducer and context. It centralizes state management and minimizes re-renders.
Here’s a basic idea:
Create a context for your app state
Set up a reducer to handle all data updates
Wrap your app in a provider that uses useReducer
Use useEffect to fetch data for each table once
Dispatch actions to update state as needed
This way, you’re only calling useRecords once per table, and React handles state updates more efficiently. It took some refactoring, but my app’s performance improved dramatically. Plus, it made the code more maintainable in the long run.
Just remember to memoize expensive computations and use callbacks wisely to prevent unnecessary re-renders. Good luck with your project!