npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-config-loader

v0.5.0

Published

React Hook for loading client-side configuration at runtime.

Downloads

25

Readme

React Config Loader

npm bundle size

React Hook for loading client-side configuration or environment variables at runtime. Stores locally and supports custom refresh times and storage.

Quickstart

npm install react-config-loader

In some section of your application, define:

// setupConfig.ts
import { setupConfig, fetchJSON } from 'react-config-loader';

// It's recommended to do this setup in it's own file for easier importing

// Define your configuration shape, for type safety.
// Javascript users can just define a config without types.

interface Config {
  API_URL: string;
  optionalVariable?: number;
}

// Define default values for all non-optional variables.

const config: Config = {
  API_URL: 'https://localhost:3000',
};

// define a method of retrieving and parsing your configuration
// react-config-loader exports helper functions, but you can use your own as long as it satisfies () => Promise<Config>
const updater = fetchJSON('config.json');

const [ConfigProvider, useConfig] = setupConfig(config, updater);

export { ConfigProvider, useConfig };

Then, in your main.tsx (or the uppermost scope you'd like your config to be available in):

// main.tsx
import { ConfigProvider } from './setupConfig.ts';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <ConfigProvider>
      <!-- other wrappers -->
      <App />
    </ConfigProvider>
  </React.StrictMode>
);

Then, in any child of ConfigProvider (in the example above, app-wide):

// MyPage.tsx
import { useConfig } from './setupConfig.ts';

export function MyPage() {
  const { config } = useConfig();
  return <span>{config.API_URL}</span>;
}

Context

In CSR applications, we usually have "environment variables" that are bundled into the application at build time. However, when deployed on a cluster, it can be a hassle to rebuild every instance of the application just to update a variable.

Solution

The general idea is to have a static "file" (i.e, independent from the application build process) that all instances query at regular intervals for the intended values. This is achieved in this application using @tanstack/react-query to provide an app-wide provider of your app's configuration.

API

react-config-loader is a simple wrapper for @tanstack/react-query, and tries to provide the same options for queries.

setupConfig<Config>(initialConfig, updater, options?)

  • initialConfig: Config: An object with all non-optional keys from Config with a default value. This is the initial value for the configuration.

  • updater: () => Promise<Config> function that returns the updated configuration. Must throw on error. See Utils.

  • options?: SetupConfigOptions

    export type ConfigQueryOptions = Omit<
      QueryObserverOptions,
      'queryKey' | 'queryFn' | 'initialData'
    >;
    
    interface SetupConfigOptions {
      queryOptions?: ConfigQueryOptions;
      buster?: string;
      persister?: Persister;
    }
    • queryOptions allows you to override @tanstack/react-query's query options, with the exception of queryKey, queryFn, initialData, because these are used internally. These are the defaults used in this package:
    const defaultOptions = {
      staleTime: 0,
      gcTime: 1000 * 60 * 60 * 24,
      refetchOnMount: true,
      refetchInterval: false,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
    };
    • buster allows you to define a custom buster in case you need to do manual cache overriding.
    • persister: allows you to use a custom Persister for storing your configuration. Uses localStorage by default.
  • Returns an array of two elements:

    • The first is a hook that returns the same values as useQuery, with an additional config that's just a reference to data, for simplicity.
    • The second is a wrapper that provides the context and storage (internally uses PersistQueryClientProvider).

Utils

Simple utility functions.

fetchConfig(url, options?): Promise<Response>

  • url: URL | string: URL to fetch to.
  • options?: fetchConfigOptions:
    interface fetchConfigOptions {
      debugInConsole?: boolean;
      fetchOptions?: RequestInit;
    }
    • debugInConsole: Sets if to log errors in the console.
    • fetchOptions: Standard options for fetch

fetchJSON<T>(url, options?): Promise<T>

Simple wrapper for fetchConfig that uses response.json() to load your data.