<!DOCTYPE html>
SolidJS Primitives: Set, Map, and Trigger
<br> body {<br> font-family: sans-serif;<br> }<br> h1, h2, h3 {<br> color: #333;<br> }<br> code {<br> background-color: #f5f5f5;<br> padding: 2px 5px;<br> border-radius: 3px;<br> }<br> .example-container {<br> border: 1px solid #ddd;<br> padding: 10px;<br> margin-bottom: 20px;<br> }<br>
SolidJS Primitives: Set, Map, and Trigger
In the previous parts of this series, we explored the fundamental building blocks of SolidJS: signals, memo, and effect. These primitives provide the core reactive capabilities that power Solid's performance and declarative nature. Today, we delve deeper into three additional primitives: Set, Map, and Trigger. These primitives offer powerful ways to manage collections and control the flow of reactivity in your SolidJS applications.
- Set
The Set primitive provides a reactive way to work with unique values. It's similar to JavaScript's built-in Set
object but with the added benefit of automatic updates whenever the set's contents change.
1.1 Creating a Set
import { createSignal, createEffect, createMemo, createSet } from 'solid-js';
const [set, setSet] = createSet([1, 2, 3]);
This code creates a new set called set
containing the initial values 1, 2, and 3. The setSet
function allows you to add, delete, or clear elements from the set.
1.2 Accessing Set Elements
You can iterate over the elements in a set using the
for...of
loop:for (const value of set) {
console.log(value);
}
1.3 Reactivity with Set
The magic of
createSet
lies in its reactivity. Any change to the set automatically triggers re-evaluation of any components or computations that depend on it.import { createSignal, createEffect, createMemo, createSet } from 'solid-js';
const [set, setSet] = createSet([1, 2, 3]);
createEffect(() => {
console.log('Set changed:', Array.from(set));
});
setSet(4); // Logs "Set changed: [1, 2, 3, 4]"
1.4 Example: Unique User List
<div>
<h2>
Unique Users
</h2>
<ul>
<for each="{set}">
{(user) =>
<li>
{user}
</li>
}
</for>
</ul>
</div>
<script>
import { createSignal, createEffect, createMemo, createSet } from 'solid-js';
import { For } from 'solid-js/web';
const [set, setSet] = createSet([]);
const [userInput, setUserInput] = createSignal('');
createEffect(() => {
const input = userInput();
if (input) {
setSet(input);
}
});
return (
<div>
<input type="text" bind:value={userInput} placeholder="Enter a user" />
{/* ... rest of the code ... */}
</div>
);
</script>
This example demonstrates how a Set
can be used to maintain a list of unique users entered by the user. The createEffect
ensures that every new user input is added to the set, while the For
loop renders each unique user in a list.
- Map
The Map primitive offers a reactive way to store and retrieve key-value pairs. It's similar to JavaScript's Map
object, but with automatic updates whenever the map's contents change.
2.1 Creating a Map
import { createSignal, createEffect, createMemo, createMap } from 'solid-js';
const [map, setMap] = createMap({
name: 'John',
age: 30
});
This creates a map called map
with two initial key-value pairs: name
and age
. The setMap
function allows you to add, delete, update, or clear entries in the map.
2.2 Accessing Map Entries
You can access individual entries in the map using the
get
method:console.log(map.get('name')); // Outputs: "John"
2.3 Reactivity with Map
Similar to
Set
, any changes to the map trigger re-evaluation of dependent components or computations.import { createSignal, createEffect, createMemo, createMap } from 'solid-js';
const [map, setMap] = createMap({
name: 'John',
age: 30
});
createEffect(() => {
console.log('Map changed:', map);
});
setMap('age', 31); // Logs "Map changed: { name: 'John', age: 31 }"
2.4 Example: Reactive User Profile
<div>
<h2>
User Profile
</h2>
<p>
Name: {map.get('name')}
</p>
<p>
Age: {map.get('age')}
</p>
</div>
<script>
import { createSignal, createEffect, createMemo, createMap } from 'solid-js';
const [map, setMap] = createMap({
name: 'Jane',
age: 25
});
return (
<div>
{/* ... rest of the code ... */}
</div>
);
</script>
This example demonstrates how a Map
can be used to store and display user profile information. The map.get('name')
and map.get('age')
expressions automatically update whenever the corresponding values in the map change, ensuring the profile data stays synchronized.
- Trigger
The Trigger primitive is a unique tool that allows you to explicitly trigger re-evaluation of memoized computations or effects. It's helpful for situations where you want to control when a computation or effect updates, rather than relying on automatic reactivity.
3.1 Creating a Trigger
import { createSignal, createEffect, createMemo, createTrigger } from 'solid-js';
const [trigger, setTrigger] = createTrigger();
This creates a trigger called trigger
. You can use the setTrigger
function to fire the trigger and initiate re-evaluation.
3.2 Using Triggers
import { createSignal, createEffect, createMemo, createTrigger } from 'solid-js';
const [count, setCount] = createSignal(0);
const [trigger, setTrigger] = createTrigger();
createMemo(() => {
console.log('Count:', count());
}, trigger);
setCount(1); // Does not log "Count: 1"
setTrigger(); // Logs "Count: 1"
In this example, the createMemo
function is associated with the trigger
. The memo only updates when the setTrigger
function is called, even though the count
signal changes.
3.3 Example: Debounced Search
<div>
<input bind:value="{searchTerm}" placeholder="Search" type="text"/>
<p>
Search Results: {searchResults}
</p>
</div>
<script>
import { createSignal, createEffect, createMemo, createTrigger } from 'solid-js';
const [searchTerm, setSearchTerm] = createSignal('');
const [trigger, setTrigger] = createTrigger();
const searchResults = createMemo(() => {
// Perform search logic using searchTerm()
// ...
}, trigger);
createEffect(() => {
const timeout = setTimeout(() => {
setTrigger();
}, 500);
return () => clearTimeout(timeout);
});
return (
<div>
{/* ... rest of the code ... */}
</div>
);
</script>
This example demonstrates how a trigger can be used to implement a debounced search. Every time the user types in the search input, the createEffect
sets a timeout before triggering the memo that performs the search. This prevents unnecessary searches while the user is still typing, improving performance.
Conclusion
SolidJS's Set, Map, and Trigger primitives provide powerful tools for managing data structures and controlling reactivity in your applications. By mastering these primitives, you gain greater control over the flow of updates and can write efficient and performant SolidJS code.
-
Set
provides a reactive way to work with unique values. -
Map
offers a reactive way to store and retrieve key-value pairs. -
Trigger
allows you to explicitly control when memoized computations or effects update.
By combining these primitives with other SolidJS features like signals, memos, and effects, you can build complex and dynamic user interfaces that are both performant and maintainable.