SolidJS provides various performance optimization techniques to significantly improve application performance:
Use createMemo to Cache Computed Results:
javascript// Bad approach - Recomputes on every render function Component() { const [items, setItems] = createSignal([]); const total = () => items().reduce((sum, item) => sum + item.price, 0); return <div>Total: {total()}</div>; } // Good approach - Use createMemo to cache function Component() { const [items, setItems] = createSignal([]); const total = createMemo(() => items().reduce((sum, item) => sum + item.price, 0)); return <div>Total: {total()}</div>; }
Batch Updates:
javascriptimport { batch } from 'solid-js'; // Bad approach - Triggers multiple updates function updateMultiple() { setName('John'); setAge(25); setEmail('john@example.com'); } // Good approach - Use batch for batch updates function updateMultiple() { batch(() => { setName('John'); setAge(25); setEmail('john@example.com'); }); }
Optimize List Rendering with Index:
javascript// For - Uses object as key (good for dynamic lists) <For each={items()} fallback={<div>No items</div>}> {(item) => <div>{item.name}</div>} </For> // Index - Uses index as key (better performance, good for static lists) <Index each={items()}> {(item, index) => <div>{item().name}</div>} </Index>
Lazy Load Components:
javascriptimport { lazy } from 'solid-js'; const HeavyComponent = lazy(() => import('./HeavyComponent')); function App() { return ( <Suspense fallback={<Loading />}> <HeavyComponent /> </Suspense> ); }
Avoid Unnecessary Reactivity:
javascript// Bad approach - Creating unnecessary signal function Component() { const [count, setCount] = createSignal(0); const doubled = createSignal(() => count() * 2); // Signal not needed return <div>{doubled()}</div>; } // Good approach - Use regular function function Component() { const [count, setCount] = createSignal(0); const doubled = () => count() * 2; return <div>{doubled()}</div>; }
Use untrack to Avoid Tracking:
javascriptimport { untrack } from 'solid-js'; createEffect(() => { const value = untrack(() => someSignal()); console.log(value); // No dependency established });
Performance Monitoring:
javascriptimport { devtools } from 'solid-js/dev'; devtools; // Enable dev tools