reactjs / reactjs/react.dev

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

Open
#7,661 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the existing React documentation and the useSettings example in the issue to identify where guidance on loading external data belongs. The finished page should explain the official approach to avoiding the initial data gap and how a hook can guarantee data availability before consumers use it.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.