Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A page on the docs site to show how to create a hook that loads data form an external source such that there would be no gap #7661

Open
Nefcanto opened this issue Mar 2, 2025 · 0 comments

Comments

@Nefcanto
Copy link

Nefcanto commented Mar 2, 2025

Let's say I want to create a hook called useSettings. This hook will load settings once from an API and cache the data.

This is a sample code:

import {
    useEffect,
    useState,
} from "react"

let cache

const useSettings = () => {

    const [settings, setSettings] = useState(cache || [])

    useEffect(() => {
        if (cache) return
        callApi("/settings")
            .then(data => {
                setSettings(data)
                cache = data
            })
    }, [])

    const getSetting = (key, fallback) => {
        const setting = settings.find(i => i.key === key)
        if (!settings) {
            return fallback
        }
        return setting.value
    }

    return {
        getSetting
    }
}

export default useSettings

This works fine when the settings are loaded. But when a component uses this hook, there is an unpredictable time at the beginning when the settings are not loaded yet, and they get the fallback value.

I searched the docs and navigated the menu items. I could not find a page as a guide on how to remove that gap.

Please add a page for this purpose. Explain what is the react's official way to solve this problem. Explain how we can make sure that when we call a hook, we are guaranteed to get the data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant