1.1.0 • Published 1 year ago

@hashiprobr/react-create-state-context v1.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

react-create-state-context

React function for simplifying the creation of state contexts

One of the most common usages of React Contexts is sharing a state. The createStateContext function creates and returns a context with the getter and the setter of a state as its value. The pair of getter and setter is memoized to avoid being recreated each time.

Please note that the usage of a state context requires its provider. A call to useContext outside of its provider will return undefined.

Peer dependencies

{
    "react": "18.2.0"
}

Install

With npm:

npm install @hashiprobr/react-create-state-context

With yarn:

yarn add @hashiprobr/react-create-state-context

If using Expo, add the module to webpack.config.js:

const createExpoWebpackConfigAsync = require('@expo/webpack-config');

module.exports = async function (env, argv) {
    const config = await createExpoWebpackConfigAsync({
        ...env,
        babel: {
            dangerouslyAddModulePathsToTranspile: [
                '@hashiprobr/react-create-state-context',
            ],
        },
    }, argv);
    return config;
};

If webpack.config.js does not exist, create it with:

expo customize:web

Example

import React, { useContext } from 'react';

import { View, Text, Button } from 'react-native';

import createStateContext from '@hashiprobr/react-create-state-context';

const CounterContext = createStateContext(0);

function MyComponent() {
    const [counter, setCounter] = useContext(CounterContext);

    return (
        <View>
            <Text>{counter}</Text>
            <Button title="+" onPress={() => setCounter(counter + 1)} />
        </View>
    );
}

export default function MyApp() {
    return (
        <CounterContext.Provider>
            <MyComponent />
        </CounterContext.Provider>
    );
}
1.1.0

1 year ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago