Languages
[Edit]
EN

React - create shared state across multiple components using custom solution

3 points
Created by:
Creg
9600

Writing applications in React it happens we need to share state between multiple components.

Thare are multiple ways to do it:

This article shows some custom hooks that lets to share state in simple way across multiple components. The motivation to state sharing can be as e.g. authentication, where user may login, logout and current state may be needed in any time and place.

The main advantages of the below solution are:

  • very small size
  • very good performance
  • posibility to read current state in any application lifecycle, what is not provided via React states. 

Practical exmaple

Runnable example is available here.

App.tsx file:

import React, {createContext, useContext} from 'react';

import {useSharedState} from './state';

const SharedState = createContext();

const Component1 = () => {
    const sharedState = useContext(SharedState);
    return (
        <div>
          <button onClick={() => sharedState.setValue('red')}>Set red</button>
          <button onClick={() => sharedState.setValue('green')}>Set green</button>
          <button onClick={() => sharedState.setValue('blue')}>Set blue</button>
        </div>
    );
};

const Component2 = () => {
    const sharedState = useContext(SharedState);
    const sharedValue = sharedState.useValue();
    return (
        <div>
          Shared value: {sharedValue}
        </div>
    );
};

const App = () => {
    const sharedState = useSharedState('default');  // replace 'default' with your default value
    return (
        <div className="app">
          <SharedState.Provider value={sharedState}>
            <Component1 />
            <Component2 />
            <Component2 />
            <Component2 />
          </SharedState.Provider>
        </div>
    );
};

export default App;

 

state.tsx file:

import {useState, useMemo, useEffect} from 'react';

export const createSharedState = (value) => {
    let _value = value;
    const _listeners = new Array();
    return {
        setValue: (value) => {
            for (const listener of _listeners) {
                listener(value);
            }
        },
        getValue: () => {
            return _value;
        },
        useValue: () => {
            const [counter, setCounter] = useState(0);
            useEffect(
                () => {
                    const listener = (value) => {
                        _value = value;
                        setCounter(counter => counter + 1);
                    };
                    _listeners.push(listener);
                    return () => {
                        var index = _listeners.indexOf(listener);
                        if (index !== -1) {
                            _listeners.splice(index, 1);
                        }
                    };
                },
                []
            )
            return _value;
        }
    };
};

export const useSharedState = (value) => {
    return useMemo(
        () => createSharedState(value),
        [value]
    );
};

 

Alternative titles

  1. React - create and share state across multiple components using custom solution
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join