Update React configuration across components

Viewed 179

I store config settings, set by the client, in local storage. When somebody updates a value, we save it to local storage. When they load the page, we grab it from local storage. The code for a sticky state is:

import React from 'react';

export default function useStickyState(key, defaultValue) {
    if (!process.browser) {
        return React.useState({})
    }

    const [value, setValue] = React.useState(() => {
        const stickyValue = window.localStorage.getItem(key);
        return stickyValue !== null
            ? JSON.parse(stickyValue)
            : defaultValue;
    });
    React.useEffect(() => {
        window.localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);
    return [value, setValue];
}

Using this, I can make a settings system pretty easily:

import useStickyState from "./useStickyState";

export default function useSettings() {
    const [config, setConfig] = useStickyState('config', {
        shortLength: 4,
        password: '',
        expirationTime: 0,
        focus: 'usability'
    })

    return [config, setConfig]
}

Then, I can access settings using:

    const [config, setConfig] = useSettings()

However. I have multiple components that use these settings. When one of them calls setConfig(), I want them all to update. Is this possible? How would one go about doing this?

The only method I can think of at the moment is polling every x seconds, which seems an awful solution.

1 Answers

You can achieve this using the React context API: load the settings from a parent component and pass them down to children using a Context Provider and the useContext hook.

I created an example that updates the config from the child and causes the parent and other children to re-render.

Related