[Recoil] Intermediate Selectors

 

interface:

export type ElementStyle = {
    position: {top: number; left: number}
    size: {width: number; height: number}
}

export type Element = {style: ElementStyle; image?: {id: number; src: string}}

 

Let's say we have this selector:

const imageInfoState = selector({
    key: 'imageInfoState',
    get: ({get}) => {
        const id = get(selectElementAtom)
        if (id === null) return

        const element = get(elementAtom(id))
        const imageId = element.image?.id
        if (imageId === undefined) return

        return callApi('image-details', {queryParams: {seed: imageId}})
    },
})

So everytime when Element changes, for example when we drag the image, position will changed,  the callApi will be triggered.

It will cause the component being re-renderred too many times.

 

How to solve the problem?

const element = get(elementAtom(id))

This code will be update everytime when Element position changes.

But we don't want trigger callApi if imageId doesn't change.

We can use intermediate selector:

const imageIdState = selector({
    key: 'imageId',
    get: ({get}) => {
        const id = get(selectElementAtom)
        if (id === null) return

        const element = get(elementAtom(id))
        return element.image?.id
    },
})

const imageInfoState = selector({
    key: 'imageInfoState',
    get: ({get}) => {
        const imageId = get(imageIdState) // use intermediate selector
        if (imageId === undefined) return

        return callApi('image-details', {queryParams: {seed: imageId}})
    },
})

 

posted @   Zhentiw  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-10-11 [SAP] 35. Cost saving
2021-10-11 [Cloud Architect] 10. Securing Access to Cloud Infrastructure
2021-10-11 [SAP] 34. System Manager
2021-10-11 [SAP] 33. Deployment and instance management
2020-10-11 [Kotlin] Open Classes and Inheritance
2020-10-11 [Kotlin] Class
2020-10-11 [Kotlin] Reverse a List with downTo
点击右上角即可分享
微信分享提示