Helper functions for React Context API inspired by @reduxjs/toolkit

Overview

react-ctx-toolkit

react-ctx-toolkit is a simple, compact, uncomplicated package inspired by @reduxjs/toolkit that includes helper functions for better coding with Context API

Table of Content

Installation

With yarn

yarn add react-ctx-toolkit

With NPM

npm install react-ctx-toolkit

Getting Started

("DECREMENT") type CounterState = { count: number } const initialState: CounterState = { count: 0, } const reducer = createReducer((builder) => { builder .addCase(increment, (state, action) => { state.count += action.payload || 1 return state }) .addCase(decrement, (state, action) => { state.count -= action.payload || 1 return state }) }) const { Provider: CounterProvider, hooks: [useCounter, useCounterDispatch], } = createContext({ displayName: "Counter", initialState }, reducer) function App() { const { count } = useCounter() const dispatch = useCounterDispatch() const handleIncrement = () => { dispatch(increment(5)) } const handleDecrement = () => { dispatch(decrement(5)) } return ( <> count: {count} ) } function Root() { return ( ) }">
const increment = createAction<number | undefined>("INCREMENT")
const decrement = createAction<number | undefined>("DECREMENT")

type CounterState = {
    count: number
}

const initialState: CounterState = {
    count: 0,
}

const reducer = createReducer<CounterState>((builder) => {
    builder
        .addCase(increment, (state, action) => {
            state.count += action.payload || 1
            return state
        })
        .addCase(decrement, (state, action) => {
            state.count -= action.payload || 1
            return state
        })
})

const {
    Provider: CounterProvider,
    hooks: [useCounter, useCounterDispatch],
} = createContext({ displayName: "Counter", initialState }, reducer)

function App() {
    const { count } = useCounter()
    const dispatch = useCounterDispatch()

    const handleIncrement = () => {
        dispatch(increment(5))
    }

    const handleDecrement = () => {
        dispatch(decrement(5))
    }

    return (
        <>
            <button onClick={handleIncrement}>Increment</button>
            count: {count}
            <button onClick={handleDecrement}>Decrement</button>
        </>
    )
}

function Root() {
    return (
        <CounterProvider>
            <App />
        </CounterProvider>
    )
}

createAction

A helper function for defining an action.

({ payload: { name, age }, })) addUser("bob", "32") // { type: "ADD_USER", payload: { name: "bob", age: "32" } } /* ----------------- */ type User = { name: string age: number } const addUser = createAction("ADD_USER") addUser({ name: "bob", age: "32" }) // { type: "ADD_USER", payload: { name: "bob", age: "32" } }">
const increment = createAction<number | undefined>("INCREMENT")
increment() // { type: "INCREMENT" }
increment(2) // { type: "INCREMENT", payload: 2 }

/* ----------------- */

const addUser = createAction("ADD_USER", (name: string, age: number) => ({
    payload: { name, age },
}))
addUser("bob", "32")
// { type: "ADD_USER", payload: { name: "bob", age: "32" } }

/* ----------------- */

type User = {
    name: string
    age: number
}

const addUser = createAction<User>("ADD_USER")
addUser({ name: "bob", age: "32" })
// { type: "ADD_USER", payload: { name: "bob", age: "32" } }

createReducer

A helper function for creating a reducer.

("DECREMENT") type StateType = { count: number } const reducer = createReducer((builder) => { builder .addCase(increment, (state, action) => { state.count += action.payload || 1 return state }) .addCase(decrement, (state, action) => { state.count -= action.payload || 1 return state }) })">
const increment = createAction<number | undefined>("INCREMENT")
const decrement = createAction<number | undefined>("DECREMENT")

type StateType = {
    count: number
}

const reducer = createReducer<StateType>((builder) => {
    builder
        .addCase(increment, (state, action) => {
            state.count += action.payload || 1
            return state
        })
        .addCase(decrement, (state, action) => {
            state.count -= action.payload || 1
            return state
        })
})

createContext

It is a helper function for creating context, provider, and hooks.

const {
    Provider: CounterProvider,
    contexts: [CounterContext, CounterDispatchContext],
    hooks: [useCounter, useCounterDispatch],
} = createContext({ displayName: "Counter", initialState }, reducer)
You might also like...
A lightweight react library that converts raw HTML to a React DOM structure.

A lightweight react library that converts raw HTML to a React DOM structure.

React-intersection-observer - Intersection observer With React
React-intersection-observer - Intersection observer With React

react-intersection-observer Package 📦 Copy and Paste the Framer Package Usage F

React-compress - This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code
React-compress - This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code

React-compress - This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code

React adblocker detect - Provides you with react hook to detect is an adblocker is enabled

React adblocker detect - Provides you with react hook to detect is an adblocker is enabled

React-native-dotenv - Load react native environment variables using import statements for multiple env files.

react-native-dotenv Load environment variables using import statements. Installation $ npm install react-native-dotenv Breaking changes: moving from v

👉 React Finger is a library of gesture events for React that allows developers to use a single set of events for both desktop and mobile devices.
👉 React Finger is a library of gesture events for React that allows developers to use a single set of events for both desktop and mobile devices.

👉 React Finger is a library of gesture events for React that allows developers to use a single set of events for both desktop and mobile devices.

Extended utils for ⚛️  React.Children data structure that adds recursive filter, map and more methods to iterate nested children.
Extended utils for ⚛️ React.Children data structure that adds recursive filter, map and more methods to iterate nested children.

React Children Utilities Recursive and extended utils for React children opaque data structure. Installation Available as a package and can be added t

CSS media queries for React

react-media react-media is a CSS media query component for React. A Media component listens for matches to a CSS media query and renders stuff based

A component for React that utilizes the Counterpart module to provide multi-lingual/localized text content.

React Translate Component Translate is a component for React that utilizes the Counterpart module and the Interpolate component to provide multi-lingu

Releases(v1.0.0)
Owner
AmirHossein Sadeqi
:)
AmirHossein Sadeqi
A helper library to use react-query more efficient, consistency

A helper library to use react-query more efficient, consistency

null 138 Nov 27, 2022
A react or react native library to call functions comparing the last time that it was called

A react or react native library to call functions comparing the last time that it was called and running it when it's really needed. Avoiding unnecessary database calls or data loads that are updated at a certain time.

Hubert Ryan 6 Nov 9, 2022
Utility functions for drawing beautiful arrows using cubic bezier paths

proto-arrows A set of utility functions for drawing beautiful arrows using cubic bezier paths. Inspired by perfect-arrows. Why proto-arrows? Because c

Kristian Muñiz 68 Nov 1, 2022
A streamlined way of creating a React.Context based on a schema. Easy to use and with 0 dependencies.

A streamlined way of creating a React.Context based on a schema. Easy to use and with 0 dependencies.

André Batista 3 Sep 6, 2022
React Context provider and hooks for Drupal, with support for Oauth2 authentication

drupal-react-oauth-provider React Context provider and hooks for Drupal, with support for Oauth2 authentication. Simplify headless Drupal REST and aut

Niall Murphy 2 Jun 1, 2022
Puro - simple react context provider

A simple utility library to create react context/provider with proper typing support

Plasmo 4 Jun 13, 2022
Article converter is an api for getting a extended html version of the content attribute provided by Article API.

Article converter is an api for getting a extended html version of the content attribute provided by Article API.

NDLA 4 Nov 28, 2022
Using eventChannel in React Redux-Saga, API in below link.

Using eventChannel in React Redux-Saga, API in below link.

James Johnson 15 Oct 1, 2022
A small utility for constructing classnames using a variant based api.

twix ?? twix is a small utility for constructing classnames using a variant based api. The API is largely copied from stitches but works with just pla

Anthony Yarbrough 7 Nov 7, 2022
Library created to format numbers easily and quickly using the Intl.NumberFormat Constructor API.

Number Formatter number-formater is a JavaScript library built to make it faster and more efficient to use the ECMAScript (Intl) API for number format

Daniel Eduardo Almagro 2 Nov 19, 2021