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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@mattyreacts/usesharedstate

v1.0.0

Published

A React hook to share state values between components in the tree

Downloads

9

Readme

useSharedState

Description

An easy to use React hook to share state variables across components in the tree. The hook returns a value and a setter the same as the useState hook. Contexts can be specified to partition the state varibales.

Installation

npm install @mattyreacts/usesharedstate

API

useSharedState<T = string>(initialState: T, key: string, context: string = 'default')

The hook to use to access the shared variable and to use for state changes

Parameters

| Name | Type | Description | Required | Default | |--------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------|----------|-----------| | initialState | <T> | The initial value to set the variable to. If this variable has already been set by a previous component then this is ignored. | Yes | - | | key | string | The name of the variable in the shared context. | Yes | - | | context | string | The name of the context to partition the shared state variables. | No | 'default' |

Returns

[value: T, (value: T) => void]

Example

ComponentA and ComponentB share a state value. Updating one will change the other.

import { useSharedState } from "@mattyreacts/usesharedstate";
import React from "react";
import { createRoot } from 'react-dom/client';

function ComponentA(): React.JSX.Element {
    const [value, setValue] = useSharedState<string>('a', 'VariableA', 'Test');
    const handleValueChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setValue(event.target.value);
    }, []);

    return (
        <input value={value} onChange={handleValueChange} />
    );
}

function ComponentB(): React.JSX.Element {
    const [value, setValue] = useSharedState<string>('a', 'VariableA', 'Test');
    const handleValueChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setValue(event.target.value);
    }, []);

    return (
        <input value={value} onChange={handleValueChange} />
    );
}

function Container(): React.JSX.Element {
    React.useEffect(() => {
        return () => clearContext('Test');
    }, []);

    return (
        <>
            <ComponentA />
            <ComponentB />
        </>
    );
}

const root = createRoot(document.getElementById('root') as HTMLElement);
root.render(<Container />);

An array with two values.

  1. The current state value
  2. A setter function to change the state value and trigger a rerender on all componentst that share the state value

getStateValue<T = string>(key: string, context: string = 'default'): T

A function to get a state value without needing a React component. Useful for retrieving values from a form for example, then uploading the values using a fetch call.

Parameters

| Name | Type | Description | Required | Default | |---------|--------|------------------------------------------------------------------|----------|-----------| | key | string | The name of the variable in the shared context. | Yes | - | | context | string | The name of the context to partition the shared state variables. | No | 'default' |

Returns

value: T The state value of the shared variable

Example

Clicking the button logs the current input value to the console

import { useSharedState, getStateValue } from "@mattyreacts/usesharedstate";
import React from "react";
import { createRoot } from 'react-dom/client';

function ComponentA(): React.JSX.Element {
    const [value, setValue] = useSharedState<string>('a', 'VariableA', 'Test');
    const handleValueChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setValue(event.target.value);
    }, []);

    return (
        <input value={value} onChange={handleValueChange} />
    );
}

function Container(): React.JSX.Element {
    React.useEffect(() => {
        return () => clearContext('Test');
    }, []);

    const handleClick = React.useCallback(() => {
        const value = getStateValue('VariableA', 'Test');
        console.log(value);
    }, []);

    return (
        <>
            <ComponentA />
            <input type="button" onClick={handleClick} value="Click" />
        </>
    );
}

const root = createRoot(document.getElementById('root') as HTMLElement);
root.render(<Container />);

setStateValue<T = string>(value: T, key: string, context: string = 'default')

A function to be able to set a shared state value and trigger a rerender on all components that use the shared value.

NB: using a key and context pair that has not been created by a component will have no effect. That is, you can only set the value of shared state variables that have already been initialised.

Parameters

| Name | Type | Description | Required | Default | |---------|-----------|------------------------------------------------------------------|----------|-----------| | value | <T> | The value to set the shared variable to. | Yes | - | | key | string | The name of the variable in the shared context. | Yes | - | | context | string | The name of the context to partition the shared state variables. | No | 'default' |

Example

Clicking the button sets the shared state value to 'test' and updates both inputs

import { useSharedState, setStateValue } from "@mattyreacts/usesharedstate";
import React from "react";
import { createRoot } from 'react-dom/client';

function ComponentA(): React.JSX.Element {
    const [value, setValue] = useSharedState<string>('a', 'VariableA', 'Test');
    const handleValueChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setValue(event.target.value);
    }, []);

    return (
        <input value={value} onChange={handleValueChange} />
    );
}

function ComponentB(): React.JSX.Element {
    const [value, setValue] = useSharedState<string>('a', 'VariableA', 'Test');
    const handleValueChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setValue(event.target.value);
    }, []);

    return (
        <input value={value} onChange={handleValueChange} />
    );
}

function Container(): React.JSX.Element {
    React.useEffect(() => {
        return () => clearContext('Test');
    }, []);

    const handleClick = React.useCallback(() => {
        setStateValue('test', 'VariableA', 'Test');
    }, []);

    return (
        <>
            <ComponentA />
            <ComponentB />
            <input type="button" onClick={handleClick} value="Click" />
        </>
    );
}

const root = createRoot(document.getElementById('root') as HTMLElement);
root.render(<Container />);