0.2.0 • Published 1 year ago

custom-react-redux v0.2.0

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

custom-react-redux

Custom-react-redux is a predictable state container for JavaScript apps. You can use custom-react-redux together with React.

Installation

Install custom-react-redux with npm

  npm install custom-react-redux

or yarn

  yarn add custom-react-redux

Basic Example

Writing reducer

Reducers are functions that take the current state and an action as arguments, and return a new state result. In other words, (state, action) => newState.

import {AnyAction} from "custom-react-redux";

export const counterReducer = (state: number = 0, action: AnyAction): number  => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1
        case 'DECREMENT':
            return state - 1
        default:
            return state
    }
}

combineReducers(reducers)

The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore.

import {combineReducers} from "custom-react-redux";
import {counterReducer} from "./counterReducer";

const rootReducer = combineReducers({
    counter: counterReducer
})

createStore(reducer)

Creates a store that holds the complete state tree of your app. There should only be a single store in your app.

import {createStore} from "custom-react-redux";

export const store = createStore(rootReducer)

export type AppRootStateType = ReturnType<typeof rootReducer>

callSubscriber

const root = ReactDOM.createRoot(
    document.getElementById('root') as HTMLElement
);

//add this code to redraw the app
const callSubscriber = () => { 
    root.render(
            <App/>
    );
}

callSubscriber() 
store.subscribe(callSubscriber) 

Provider

Added Provider into your app

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {Provider} from "custom-react-redux";
import {store} from "./store";

const root = ReactDOM.createRoot(
    document.getElementById('root') as HTMLElement
);

const callSubscriber = () => {
    root.render(
        <Provider store={store}> 
            <App/>
        </Provider> 
    );
}

callSubscriber()
store.subscribe(callSubscriber)

useDispatch()

This hook returns a reference to the dispatch function from the store. You may use it to dispatch actions as needed.

import {useDispatch} from "custom-react-redux";


const dispatch = useDispatch()
dispatch({type: 'INCREMENT'})

useSelector()

Allows you to extract data from the store state, using a selector function.

import {useSelector} from "custom-react-redux";


 const counter = useSelector<AppRootStateType, number>(state => state.counter)
0.2.0

1 year ago

0.1.8

1 year ago

0.1.7

1 year ago

0.1.6

1 year ago

0.1.5

1 year ago

0.1.4

1 year ago

0.1.3

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.1.0

1 year ago