react-state-hook

1.1.2 • Public • Published

npm version Build Status Coverage Status js-standard-style MIT License

React Flux Hook

This repo is derived from the following Medium Article.

Installation

npm

npm i -S react-state-hook

yarn

yarn add react-state-hook

Usage

Enhance Your App with Global State

import { StateProvider } from 'react-state-hook'

const App = () => {
	const initialState = {
		theme: { primary: 'green' },
	}

	const reducer = (state, action) => {
		switch (action.type) {
			case 'changeTheme':
				return {
					...state,
					theme: action.newTheme,
				}

			default:
				return state
		}
	}

	return (
		<StateProvider initialState={initialState} reducer={reducer}>
			// App content ...
		</StateProvider>
	)
}

Then Use and Update the State Inside Your App

import { useStateValue } from 'react-state-hook'

const ThemedButton = () => {
  const [{ theme }, dispatch] = useStateValue()
  return (
    <Button
      primaryColor={theme.primary}
      onClick={() => dispatch({
        type: 'changeTheme',
        newTheme: { primary: 'blue'}
      })}
    >
      Make me blue!
    </Button>
  )
}```

For Class Componnets

import React, { Component } from 'react'
import { StateContext } from 'react-state-hook'

class ThemedButton extends Component {
  static contextType = StateContext
  render() {
    const [{ theme }, dispatch] = this.context;
    return (
      <Button
        primaryColor={theme.primary}
        onClick={() => dispatch({
          type: 'changeTheme',
          newTheme: { primary: 'blue'}
        })}
      >
        Make me blue!
      </Button>
    )
  }
}

Combining Reducers

import userReducer from './reducers/user'
import basketReducer from './reducers/basket'

const mainReducer = ({ user, basket }, action) => {
	// middleware goes here, i.e calling analytics service, etc.

	return {
  	user: userReducer(user, action),
  	basket: basketReducer(basket, action)
	}
}

Package Sidebar

Install

npm i react-state-hook

Weekly Downloads

13

Version

1.1.2

License

MIT

Unpacked Size

6.16 kB

Total Files

4

Last publish

Collaborators

  • edward-hong