React Grid with Formula Dependencies and Virtual Rendering
Data Structure DesignModel answerLast updated
Build a React component that displays a large editable grid, evaluates cell formulas with references, detects cycles, and renders only visible rows.
You need to create a React component that displays a spreadsheet-like grid where users can edit cells and enter formulas that reference other cells.
What You Need to Build
Create a Spreadsheet component that accepts these props:
interface SpreadsheetProps {
rowCount: number; // Total number of rows
colCount: number; // Number of columns (1-26 for A-Z)
cellWidth: number; // Width of each cell in pixels
cellHeight: number; // Height of each cell in pixels
viewportWidth: number; // Container width
viewportHeight: number; // Container height
overscan?: number; // Extra rows/cols to render beyond visible area (default: 3)
initialData?: Record<string, string>; // Starting cell values like { "A1": "Hello" }
}
Core Features
1. Cell Editing and Display
- Columns are labeled A through Z, rows are numbered starting from 1
- Users can click a cell to edit its raw content
- Display the evaluated result when not editing
2. Formula System
- Any cell value starting with
=is treated as a formula - Formulas can reference other cells (e.g.,
A1,B23) and concatenate strings with& - String literals are enclosed in double quotes:
"text" - Example:
=A1 & " " & B2concatenates the values from A1 and B2 with a space between
3. Error Handling
- If a formula references a non-existent cell, show
#REF! - If circular dependencies exist (A1 depends on B1, B1 depends on A1), show
#CYCLE!for all cells in the cycle
4. Performance Requirements
- Virtual rendering: With up to 50,000 rows, you cannot render all cells as DOM elements. Only render cells currently visible in the viewport plus a small buffer (overscan)
- Selective re-rendering: When a user edits cell A1, only A1 and cells that depend on A1 (directly or transitively) should re-evaluate. Independent cells should not re-render
Example Behavior
Starting state:
- A1:
"Hello" - B1:
"World" - C1:
"=A1 & \" \" & B1" - D1:
"=C1 & \"!\""
Display shows:
- A1: Hello
- B1: World
- C1: Hello World
- D1: Hello World!
User changes A1 to "Hi":
- Only A1, C1, and D1 recalculate
- B1 and unrelated cells don't re-render
- New display: C1 shows "Hi World", D1 shows "Hi World!"
Constraints
- Maximum 50,000 rows
- Maximum 26 columns (A-Z)
- Formula syntax includes only: cell references, string literals in quotes, and
&operator
Hints
Hint 1
Build a dependency graph tracking which cells reference which other cells—this enables targeted updates when a cell changes.
Hint 2
For virtualization, calculate which row and column indices are visible given the scroll position, then render only those plus overscan buffer.
Hint 3
Use React.memo or useMemo to prevent cell components from re-rendering unless their own data or dependencies change.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines three distinct challenges: formula parsing and evaluation, dependency tracking for selective updates, and virtual rendering for performance.
1. Data Structure Design
Cell Storage: Use a Map or plain object keyed by cell ID (e.g., "A1") storing raw input strings.
Dependency Graph: Maintain two structures:
dependencies: maps each cell to the set of cells it directly referencesdependents: reverse mapping—maps each cell to the set of cells that reference it
When A1 changes, walk the dependents graph to find all cells transitively affected.
Evaluation Cache: Store computed values separately from raw inputs to avoid re-parsing formulas unnecessarily.
2. Formula Parsing and Evaluation
Tokenization: Parse formula strings to extract:
- Cell references: regex
[A-Z][1-9][0-9]* - String literals: content between
"characters - Operators:
&for concatenation
Evaluation Algorithm:
- If the cell value doesn't start with
=, return it as-is - Otherwise, tokenize the formula
- For each cell reference token, recursively evaluate that cell
- Track evaluation stack to detect cycles—if you encounter a cell already in the stack, return
#CYCLE! - If a referenced cell doesn't exist, substitute
#REF! - Concatenate all tokens
Cycle Detection: Use a Set passed down through recursive evaluation calls. Before evaluating cell X, add X to the set. After evaluation, remove it. If X is already in the set when you try to evaluate it, you've found a cycle.
3. Dependency Tracking and Selective Updates
When a cell's raw value changes:
- Parse the new formula to extract references
- Update the dependency graph: remove old edges, add new edges
- Perform a breadth-first or depth-first traversal of dependents starting from the changed cell
- Invalidate cached values for all affected cells
- Trigger re-evaluation only for those cells
Use React state or a state management library. The key optimization: each cell component should be memoized and only re-render when its own cached value changes.
4. Virtualization
Visible Range Calculation:
startRow = floor(scrollTop / cellHeight) - overscan
endRow = ceil((scrollTop + viewportHeight) / cellHeight) + overscan
startCol = floor(scrollLeft / cellWidth) - overscan
endCol = ceil((scrollLeft + viewportWidth) / cellWidth) + overscan
Rendering Strategy:
- Create a scrollable container with total dimensions
rowCount * cellHeightbycolCount * cellWidth - Inside, absolutely position only the visible cells based on their row/column indices
- Listen to scroll events and recalculate the visible range, triggering a re-render of the cell list
Implementation Pattern:
const visibleCells = [];
for (let row = startRow; row <= endRow; row++) {
for (let col = startCol; col <= endCol; col++) {
const cellId = columnLabel(col) + row;
visibleCells.push(
<Cell
key={cellId}
id={cellId}
style={{
position: 'absolute',
left: col * cellWidth,
top: row * cellHeight,
width: cellWidth,
height: cellHeight
}}
value={getCachedValue(cellId)}
onChange={handleCellChange}
/>
);
}
}
5. React Component Structure
const Spreadsheet: React.FC<SpreadsheetProps> = (props) => {
const [cellData, setCellData] = useState<Map<string, string>>(/* initial */);
const [scroll, setScroll] = useState({ top: 0, left: 0 });
const dependencyGraph = useRef({ dependencies: {}, dependents: {} });
const evalCache = useRef(new Map());
const handleScroll = (e) => {
setScroll({ top: e.target.scrollTop, left: e.target.scrollLeft });
};
const updateCell = (cellId: string, newValue: string) => {
// Update raw data
// Recompute dependencies
// Invalidate affected cells in cache
// Trigger re-render
};
const visibleRange = computeVisibleRange(scroll, props);
const visibleCells = renderVisibleCells(visibleRange);
return (
<div onScroll={handleScroll} style={{ overflow: 'auto', ... }}>
<div style={{ position: 'relative', width: totalWidth, height: totalHeight }}>
{visibleCells}
</div>
</div>
);
};
const Cell = React.memo(({ id, value, onChange, style }) => {
const [editing, setEditing] = useState(false);
// Render logic
});
Complexity Analysis
-
Time:
- Cell update: O(D) where D is the number of dependent cells (typically small)
- Formula evaluation: O(R) where R is the number of references in the formula
- Rendering: O(V) where V is the number of visible cells (constant given fixed viewport)
-
Space: O(N × M) for cell storage where N is rows and M is columns, plus O(E) for dependency edges
Common Mistakes
- Re-rendering everything: Not memoizing cell components or not tracking dependencies leads to O(visible cells) re-renders per edit
- Missing cycle detection: Infinite recursion crashes the app when formulas reference each other
- Rendering all cells: Without virtualization, 50,000 rows would create 1.3M DOM nodes (50k × 26), freezing the browser
- Stale closures: In React, dependency graph refs must be kept up-to-date; derived state should be computed in render or via useMemo
- String parsing edge cases: Quotes within strings, malformed formulas, and missing references need explicit handling
This design balances complexity with performance: a dependency graph provides O(affected cells) updates, virtualization keeps DOM size constant, and React memoization prevents unnecessary reconciliation.