Grids are widely adopted in app development. They form an orderly and neat grid layout through intersecting horizontal and vertical lines. Grids are suitable for displaying various types of data such as images, media files, and shopping items. During grid scrolling, the child components incur performance costs in measurement and rendering. This topic describes how to develop highly smooth scrolling grid pages using the third-party library ScrollComponents in scenarios such as cross-page reuse, first-screen rendering acceleration, and pull-down refresh.
ScrollComponents is designed to address issues of component reuse and implements high-performance scrolling through minimal code. With this library, you do not need to focus on reuse pool management or interaction details of other performance optimization solutions. For details about how to install and use ScrollComponents, see the ScrollComponents usage guide. ScrollComponents provides the following features:
ScrollComponents encapsulates NodeContainer and FrameNode at the bottom layer, and implements capabilities such as lazy loading, component reuse, and component pre-creation using NodeAdapter, BuildNode, and the custom reuse pool. In addition, it provides view management components such as WaterFlowManager, ListManager, and GridManager and various system scrollable component capabilities to achieve high-performance scrolling. You only need to pass in a data source and a view manager to quickly implement lazy loading and component reuse, focusing more on service implementation.
Figure 1 shows the overall flowchart of RecyclerView. When a node is removed from the viewable area, NodeAdapter notifies the view manager to recycle the component, which is processed by NodeFactory and eventually stored in the component reuse pool. When NodeAdapter notifies the view manager that a new node is required, NodeFactory requests a node from the reuse pool, updates and assembles the components, and returns the node. Finally, NodeAdapter adds the returned node to the viewable area.

GridManager, a custom grid view manager, only provides basic view capabilities. To utilize the component reuse feature, you need to define a class that inherits from GridManager and implement the onWillCreateItem() API. For details, see 4. Register the child node template. Sample code:
import { GridManager, NodeItem, RecyclerView } from "@hadss/scroll_components";
// ...
@Component
export default struct WordGridComponent {
gridViewManager: GridViewManager = new GridViewManager({ defaultNodeItem: 'word', context: this.getUIContext() });
// ...
}
class GridViewManager extends GridManager {
onWillCreateItem(index: number, data: WordViewModel) {
// get node based on identifier 'word' from recycle pool.
let node: NodeItem<WordCellData> | null = this.dequeueReusableNodeByType('word');
node.setData({ word: data })
return node;
}
}
To quickly create a grid layout with ScrollComponents and improve scrolling efficiency through lazy loading and pre-creation, without considering component reuse, use GridManager provided by ScrollComponents. For details, see the ScrollComponents usage guide.
During page initialization, call the setViewStyle() API of the view manager to set view properties.
aboutToAppear(): void {
this.gridViewManager.setViewStyle()
.alignItems(GridItemAlignment.STRETCH);
this.gridViewManager.setViewStyle()
.columnsTemplate('repeat(auto-fill, 70)')
.columnsGap(5)
.rowsGap(5);
// ...
} import { GridManager, NodeItem, RecyclerView } from "@hadss/scroll_components";
import WordGridViewModel from "../viewModel/WordGridViewModel";
import WordViewModel from "../viewModel/WordViewModel";
// ...
@Component
export default struct WordGridComponent {
gridViewManager: GridViewManager = new GridViewManager({ defaultNodeItem: 'word', context: this.getUIContext() });
viewModel: WordGridViewModel = new WordGridViewModel(this.gridViewManager);
aboutToAppear(): void {
// ...
// associates the builder with the identifier 'word'.
this.gridViewManager.registerNodeItem('word', wrapBuilder(buildWordCell));
this.viewModel.loadData();
}
build() {
Column() {
// place the grid in a column.
RecyclerView({
viewManager: this.gridViewManager
})
}
.width('100%')
}
}
@Observed
export default class WordGridViewModel {
@Track data: WordViewModel[] = [];
gridViewManager?: GridManager;
// ...
async loadData() {
// simulated request data.
for (let index = 0; index < 15; index++) {
let viewModel: WordViewModel = new WordViewModel();
// ...
this.data.push(viewModel);
}
this.gridViewManager?.setDataSource(this.data);
}
}
1. The @builder function used in the registerNodeItem() method can only be used globally.
2. this.gridViewManager.preCreate() can be used to pre-create a component only after the node template is registered.
After customizing a template, you need to implement the onWillCreateItem() API when defining the view manager. In this API, you can obtain reusable nodes by calling dequeueReusableNodeByType(). You also need to update data in the aboutToReuse lifecycle of the reused component.
If the reused grid components have the same structure, register the node template.
import WordCell from "./WordCellComponent";
/**
* define item template.
*
* @param data data of node
*/
@Builder
function buildWordCell(data: WordCellData) {
WordCell({ word: data.word })
}
@Component
export default struct WordGridComponent {
// ...
aboutToAppear(): void {
// ...
// associates the builder with the identifier 'word'.
this.gridViewManager.registerNodeItem('word', wrapBuilder(buildWordCell));
// ...
}
// ...
}
class GridViewManager extends GridManager {
onWillCreateItem(index: number, data: WordViewModel) {
// get node based on identifier 'word' from recycle pool.
let node: NodeItem<WordCellData> | null = this.dequeueReusableNodeByType('word');
node.setData({ word: data })
return node;
}
} If the structures of reused grid components are largely identical but have minor variations, these differences can prevent full component reuse. ScrollComponents provides PartReuse to ensure that components with partial matches are still eligible for reuse.

You can check whether the reuse is successful based on the log "generateItem reuse" in Figure 3.

Child component 1:
// child component in item
@Component
export default struct UserCardComponent {
@State user: UserInfoViewModel = new UserInfoViewModel();
aboutToReuse(params: Record<string, ESObject>) {
let input = params as CardCellData;
this.user = input.user;
}
build() {
// ...
}
}
@Builder
export function buildUserCard(params: CardCellData) {
UserCardComponent({ user: params.user })
} Child component 2:
// child component in item
@Component
export default struct ManagerCardComponent {
@State user: UserInfoViewModel = new UserInfoViewModel();
aboutToReuse(params: Record<string, ESObject>) {
let input = params as CardCellData;
this.user = input.user;
}
build() {
// ...
}
}
@Builder
export function buildManagerCard(params: CardCellData) {
ManagerCardComponent({ user: params.user })
} Grid component:
// item component
@Component
export default struct CardComponent {
@State user: UserInfoViewModel = new UserInfoViewModel();
aboutToReuse(params: Record<string, ESObject>) {
let input = params as CardCellData;
this.user = input.user;
}
// ...
build() {
Column() {
if (this.user.role === 'manager') {
// when need to reuse a subcomponent, use PartReuse to encapsulate it.
PartReuse({
type: 'manager',
builder: wrapBuilder(buildManagerCard),
data: {
user: this.user
}
})
} else {
PartReuse({
type: 'user',
builder: wrapBuilder(buildUserCard),
data: {
user: this.user
}
})
}
}
.bindContextMenu(this.optMenu(), ResponseType.LongPress)
.width('90%')
.height(80)
}
}
@Builder
export function buildCard(data: CardCellData) {
CardComponent({ user: data.user })
} Component registration:
// card grid view
@Component
export default struct CardGridComponent {
// ...
aboutToAppear(): void {
// ...
// register the reusable template.
this.gridViewManager.registerNodeItem("card", wrapBuilder(buildCard));
this.gridViewManager.registerNodeItem("user", wrapBuilder(buildUserCard));
this.gridViewManager.registerNodeItem("manager", wrapBuilder(buildManagerCard));
// ...
}
// ...
build() {
Stack({ alignContent: Alignment.Bottom }) {
// main grid
RecyclerView({
viewManager: this.gridViewManager
})
// ...
}
}
}
/**
* grid manager class
*/
class GridViewManager extends GridManager {
onWillCreateItem(index: number, data: UserInfoViewModel): NodeItem<CardCellData> | null {
let node: NodeItem<CardCellData> | null = this.dequeueReusableNodeByType('card');
node?.setData({ user: data });
return node;
}
} If the structures of GridItem components differ significantly, due to major layout variations, a large number of divergent components, or different component types, making direct reuse difficult, you can define multiple reuse templates.
@Component
export default struct WorkComponent {
// ...
aboutToAppear(): void {
// ...
this.gridViewManager.registerNodeItem("video", wrapBuilder(buildVideoWork));
this.gridViewManager.registerNodeItem("picture", wrapBuilder(buildPictureWork));
this.gridViewManager.registerNodeItem("photoContainer", wrapBuilder(buildPhoto));
// ...
}
// ...
}
/**
* grid manager class
*/
class GridViewManager extends GridManager {
onWillCreateItem(index: number, data: WorkViewModel): NodeItem<WorkCellData> | null {
// select the corresponding template according to the data type.
let node: NodeItem<WorkCellData> | null = this.dequeueReusableNodeByType(data.type);
node?.setData({ work: data });
return node;
}
} Grids may be reused across multiple pages, for example, tabs. ScrollComponents provides global reuse capabilities to support this requirement.
RecyclerView generates a RecycledPool object by default. A singleton reuse pool can be defined to store this pool, making it accessible across pages. The following singleton is for reference only. You can encapsulate it based on actual demands.
import { RecycledPool } from '@hadss/scroll_components';
export class Utils {
// ...
private static utils_: Utils;
nodePool: RecycledPool | null = null;
// ...
} GridManager provides the getRecyclePool() method to obtain the RecycledPool object and store it in the global singleton.
@Component
export default struct WorkComponent {
// ...
aboutToAppear(): void {
if (Utils.getInstance().nodePool) {
this.gridViewManager.registerRecyclePool(Utils.getInstance().nodePool!);
} else {
// save recycle pool.
Utils.getInstance().nodePool = this.gridViewManager.getRecyclePool();
}
// ...
}
// ...
} Use the registerRecyclePool API to register the RecyclePool object in the global singleton with the grid view class object defined for the current page. This enables reuse pool sharing across RecyclerView components on different pages.
@Component
export default struct PhotoGridComponent {
// ...
aboutToAppear(): void {
// ...
if (Utils.getInstance().nodePool) {
// register recycle pool.
this.gridViewManager.registerRecyclePool(Utils.getInstance().nodePool!);
} else {
Utils.getInstance().nodePool = this.gridViewManager.getRecyclePool();
}
// ...
// register template after register recycle pool.
this.gridViewManager.registerNodeItem('photoContainer', wrapBuilder(buildPhoto));
// ...
}
// ...
} When users first open a grid page after a cold start, a blank screen or white patches may appear due to numerous media resources such as images or videos contained in the page, which may take a few seconds to load, resulting in the content gradually appearing only after the wait. The ScrollComponents library supports component pre-creation. With this feature enabled, users can see the text and image skeletons immediately after the page opens, thereby reducing stuttering.
The core code is as follows:
aboutToAppear(): void {
// ...
// register the reusable template.
this.gridViewManager.registerNodeItem("card", wrapBuilder(buildCard));
this.gridViewManager.registerNodeItem("user", wrapBuilder(buildUserCard));
this.gridViewManager.registerNodeItem("manager", wrapBuilder(buildManagerCard));
// key point: `preCreate()` pre-creates the reusable template,
// which must be registered before the reusable template.
this.gridViewManager.preCreate("card", 25);
this.gridViewManager.preCreate("user", 10);
this.gridViewManager.preCreate("manager", 30);
// ...
} To compare the completion latencies of loading identical data in the post-cold-start scenario, a 1-second delay is added to simulate the network request scenario that occurs after a cold start.
@Reusable: During the network request, the main thread exhibited long idle durations. After the request completed, the time taken to render the first-screen components was relatively long.

ScrollComponents: During the network request, the main thread exhibited minimal idle durations. After the request completed, the time taken to render the first-screen components was relatively short.

How to Implement | Cold Start Completion Latency | Main Thread Idle Duration | First-Screen Component Creation Duration |
|---|---|---|---|
ScrollComponents | 2.5s | 281 ms | 223 ms |
@Reusable | 2.8s | 997 ms | 467 ms |
Conclusion: In cold start scenarios, ScrollComponents outperforms the built-in @Reusable implementation in completion latency, delivering an overall reduction in latency of 300 ms.
Pull-to-refresh is a critical feature for enhancing user experience, requiring both seamless data loading and maintaining smooth interaction effects. In this scenario, you are advised to use lazy loading for updates to prevent UI rendering blocks caused by media resource loading. For details about the effect, see Example 6: Implementing Pull-Down-to-Refresh and Pull-Up-to-Load-More.
@Component
export default struct WorkComponent {
// ...
gridViewManager: GridViewManager = new GridViewManager({ defaultNodeItem: 'video', context: this.getUIContext() });
@State viewModel: WorkGridViewModel = new WorkGridViewModel(this.gridViewManager);
// ...
build() {
Refresh({ refreshing: $$this.viewModel.isRefresh, builder: this.refreshBuilder() }) {
// ...
// main grid
RecyclerView({
viewManager: this.gridViewManager
})
// ...
}
// ...
.onRefreshing(() => {
this.viewModel.refreshData();
})
}
} @Observed
export default class WorkGridViewModel {
// ...
@Track isRefresh: boolean = false;
// ...
gridViewManager?: GridManager;
constructor(gridViewManager: GridManager) {
this.gridViewManager = gridViewManager;
}
loadData() {
// ...
// refresh data source
this.gridViewManager?.nodeAdapter.deleteData(0, lastLength);
this.gridViewManager?.setDataSource(this.data);
}
/**
* refresh display data
*/
refreshData() {
setTimeout(() => {
this.loadData();
this.isRefresh = false;
}, 1000);
}
// ...
} When a grid page involves large volumes of data and requires pagination or batched requests, a load-more effect can be implemented by leveraging the lazy loading capability provided by ScrollComponents. For details about the effect, see Example 6: Implementing Pull-Down-to-Refresh and Pull-Up-to-Load-More.
@Component
export default struct WorkComponent {
// ...
gridViewManager: GridViewManager = new GridViewManager({ defaultNodeItem: 'video', context: this.getUIContext() });
@State viewModel: WorkGridViewModel = new WorkGridViewModel(this.gridViewManager);
// ...
aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle()
.onReachEnd(() => {
// listen the scroll position.
this.viewModel.loadMore();
});
// ...
}
// ...
} @Observed
export default class WorkGridViewModel {
// ...
@Track isLoading = false;
gridViewManager?: GridManager;
// ...
/**
* mock load more data when reach end
*/
loadMore() {
if (this.worksCount <= this.data.length) {
return;
}
this.isLoading = true;
setTimeout(() => {
if (this.worksCount > this.data.length) {
for (let index = 0; index < 20; index++) {
if (this.data.length < this.worksCount) {
this.gridViewManager?.nodeAdapter.pushData([this.generateData()]);
this.isLoading = false;
}
}
}
this.isLoading = false;
}, 500);
}
// ...
/**
* generate mock Work
*
* @returns work data
*/
generateData(): WorkViewModel {
// ...
}
} aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle()
.columnsTemplate(this.viewModel.columnsTemplate);
// ...
} aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle()
.layoutDirection(GridDirection.Row);
// ...
} Data can be displayed in a grid by adding components such as Text to the GridItem components. For details about the effect, see Displaying Data in a Grid Layout.
Add the Text component to the GridItem component to display data.
// item component
@Component
export default struct WordCell {
@State word: WordViewModel = new WordViewModel();
aboutToReuse(params: Record<string, ESObject>) {
let input = params as WordCellData;
this.word = input.word;
}
build() {
// ...
// define a text component that displays data in a cell after receiving it.
Text(this.word.value)
.height("15%")
// ...
}
} The horizontal spacing between grid items is referred to as row spacing, while the vertical spacing is referred to as column spacing. The row and column spacing of a grid layout can be configured using the rowsGap and columnsGap properties. For details about the effect, see Setting the Gap Between Rows and Columns.
Set columnsGap and rowsGap to 8 vp respectively.
aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle()
.columnsGap(8) // set column spacing to 8vp.
.rowsGap(8); // set row spacing to 8vp.
// ...
} You can use columnsTemplate and rowsTemplate to build a scrollable grid. For details about the effect, see Building a Scrollable Grid Layout.
Set the grid as a three-column equal-width grid through columnsTemplate.
aboutToAppear(): void {
// ...
// only set the columnsTemplate property. when the content exceeds the grid area, it can be scrolled vertically.
this.gridViewManager.setViewStyle()
.columnsTemplate("1fr 1fr 1fr");
// ...
} You can control scrolling by setting the Scroller object. For details about the effect, see Controlling the Scrolling Position.
// card grid view
@Component
export default struct CardGridComponent {
scroller: Scroller = new Scroller();
gridViewManager: GridViewManager = new GridViewManager({ defaultNodeItem: "card", context: this.getUIContext() });
@State viewModel: CardGridViewModel = new CardGridViewModel(this.gridViewManager, this.scroller);
aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle(this.scroller);
// ...
}
// ...
build() {
Stack({ alignContent: Alignment.Bottom }) {
// main grid
RecyclerView({
viewManager: this.gridViewManager
})
Row() {
// button goto pre page
Button() {
// ...
}
// ...
.onClick(() => {
this.viewModel.prePage();
})
// button goto next page
Button() {
// ...
}
// ...
.onClick(() => {
this.viewModel.nextPage();
})
}
// ...
}
}
} @Observed
export default class CardGridViewModel {
// ...
gridViewManager?: GridManager;
scroller?: Scroller;
constructor(gridViewManager: GridManager, scroller: Scroller) {
this.gridViewManager = gridViewManager;
this.scroller = scroller;
}
// ...
/**
* goto pre page
*/
prePage() {
this.scroller?.scrollPage({
next: false,
animation: true
});
}
/**
* goto next page.
*/
nextPage() {
this.scroller?.scrollPage({
next: true,
animation: true
});
}
} The nested scrolling effect is configured through the nestedScroll property and onScrollFrameBegin callback. For details about the effect, see Example 4: Implementing Nested Scrolling in a Grid.
Set the nested scrolling mode for both forward and backward directions through the nestedScroll property to achieve scrolling synchronization with the parent component.
aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle(this.scroller)
.nestedScroll({
scrollForward: NestedScrollMode.PARENT_FIRST,
scrollBackward: NestedScrollMode.SELF_FIRST
});
// ...
} The drag-and-drop effect for grid items can be achieved by handling drag events and implementing data exchange logic. For details about the effect, see Example 5: Implementing Dragging in a Grid.
@Component
export default struct WorkComponent {
// ...
@State workModel: WorkViewModel = new WorkViewModel();
aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle()
.editMode(true)
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => {
let model = this.viewModel.getItemData(itemIndex);
this.workModel = model;
return this.buildDrag();
})
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => {
if (!isSuccess) {
return;
}
this.viewModel.move(itemIndex, insertIndex);
});
// ...
}
@Builder
buildDrag() {
Column() {
buildVideoWork({ work: this.workModel });
}
.width(125)
}
// ...
}
@Observed
export default class WorkGridViewModel {
// ...
gridViewManager?: GridManager;
// ...
/**
* move work index
*
* @param fromIndex source index
* @param toIndex target index
*/
move(fromIndex: number, toIndex: number) {
if (toIndex >= this.data.length) {
return;
}
this.gridViewManager?.nodeAdapter.moveData(fromIndex, toIndex);
}
// ...
} Adaptive layout effects are achieved through the properties layoutDirection, maxCount, minCount, and cellLength. These properties take effect only when neither rowsTemplate nor columnsTemplate is set. For details about the effect, see Example 6: Implementing Adaptive Grid Layout.
Set maxCount, minCount, and cellLength to implement the adaptive layout.
aboutToAppear() {
this.gridViewManager.setViewStyle()
.width("90%")
.columnsGap(10)
.rowsGap(5)
.maxCount(10)
.minCount(2)
.cellLength(0)
.border({ color: Color.Black, width: 1 });
// ...
} auto-fill, auto-fit, and auto-stretch in the columnsTemplate property can be used to achieve automatic adjustment of the number of columns. For details about the effect, see Example 8: Using Adaptive Column Count Settings.
Set columnsTemplate to repeat(auto-fill, 70).
aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle()
.columnsTemplate('repeat(auto-fill, 70)')
.columnsGap(5)
.rowsGap(5);
// ...
} The alignItems property can be configured to make all grid items in a row adopt the height of the tallest item in that same row. For details about the effect, see Setting Grid Item Heights Based on the Tallest Item in the Current Row.
Set alignItems to GridItemAlignment.STRETCH to make all items in a row match the height of the tallest item.
aboutToAppear(): void {
this.gridViewManager.setViewStyle()
.alignItems(GridItemAlignment.STRETCH);
// ...
} You can enable the edge fading effect using the fadingEdge property. For details about the effect, see Example 10: Setting Edge Fading.
Enable edge fading and set the edge fading length to 40 vp.
aboutToAppear(): void {
// ...
this.gridViewManager.setViewStyle()
.fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(40) })
// ...
} You can use the gridViewManager.setItemViewStyle() API to set the grid item style. For details about the effect, see Example 2: Setting the Grid Item Style.
Use gridViewManager.setItemViewStyle() to set the style and attributes of a grid item.
aboutToAppear(): void {
// ...
this.gridViewManager.setItemViewStyle((gridItem) => {
gridItem({ style: GridItemStyle.PLAIN })
.width(80) // set the cell width to 80vp.
.backgroundColor($r('app.color.home_background_color'))
.selectable(false)
});
// ...
} The delete button is displayed upon a long press gesture on an item. The corresponding item can be deleted by handling the button's tap event.
// item component
@Component
export default struct CardComponent {
@State user: UserInfoViewModel = new UserInfoViewModel();
// ...
@Builder
optMenu() {
Row() {
Button() {
// ...
}
.backgroundColor(Color.Red)
.onClick(() => {
this.getUIContext().getHostContext()?.eventHub.emit(CommonConstants.EVENT_REMOVE_ITEM, this.user.id);
})
}
// ...
}
build() {
Column() {
// ...
}
.bindContextMenu(this.optMenu(), ResponseType.LongPress)
// ...
}
} aboutToAppear(): void {
// ...
// register 'delete' event listener.
this.getUIContext().getHostContext()?.eventHub.on(CommonConstants.EVENT_REMOVE_ITEM, (id: number) => {
animateToImmediately({ duration: 500 }, () => {
this.viewModel.deleteData(id);
})
});
// ...
}
aboutToDisappear(): void {
// when the page is destroyed, cancel the deletion listener.
this.getUIContext().getHostContext()?.eventHub.off(CommonConstants.EVENT_REMOVE_ITEM);
this.viewModel.destroy();
} /**
* delete data by user id
*
* @param id user id
*/
deleteData(id: number) {
for (let index = 0; index < this.data.length; index++) {
let model = this.data[index];
if (model.id === id) {
// delete components and data
this.gridViewManager?.nodeAdapter.deleteData(index);
return;
}
}
}