• Stars
    star
    643
  • Rank 70,000 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸš€ react-contextual is a small (less than 1KB) helper around React 16s new context api

Build Status codecov npm version

npm install react-contextual

Why πŸ€”

  • consume and create context with ease, every kind of context, no matter which or whose or how many providers
  • a cooked down redux-like store pattern with setState semantics and central actions

Click this link for a detailed explanation.

If you just need a light-weight no-frills store 🎰

Examples: Counter | Global setState | Async actions |Β Memoization/Reselect | Multiple stores | External store

Pass a store (which stores some state and actions to update the state) to Provider. Then receive the props in the store either by using a HOC or render-props.

Render props

import { Provider, Subscribe } from 'react-contextual'

const store = {
  count: 0,
  up: () => state => ({ count: state.count + 1 }),
  down: () => state => ({ count: state.count - 1 }),
}

const App = () => (
  <Provider {...store}>
    <Subscribe>
      {props => (
        <div>
          <h1>{props.count}</h1>
          <button onClick={props.up}>Up</button>
          <button onClick={props.down}>Down</button>
        </div>
      )}
    </Subscribe>
  </Provider>
)

Higher Order Component

import { Provider, subscribe } from 'react-contextual'

const View = subscribe()(props => (
  <div>
    <h1>{props.count}</h1>
    <button onClick={props.up}>Up</button>
    <button onClick={props.down}>Down</button>
  </div>
))

const App = () => (
  <Provider {...store}>
    <View />
  </Provider>
)

With decorator

@subscribe()
class View extends React.PureComponent {
  // ...
}

Default store vs External store

If you declare your store like above it becomes the default internal context, and is available by default to all subscribers. There is no need to explicitely refer to it when you subscribe to it.

When you need your store to be "external" so that you can refer to it and/or change its props from anywhere, you can declare it via createStore. This also comes in handy when you need multiple stores.

There are a few key differences:

  • the store must be passed to its provider with the store property
  • it must be referred to either as first argument in subscribe or the to prop in Subscribe
import { Provider, createStore, subscribe } from 'react-contextual'

const externalStore = createStore({
  text: 'Hello',
  setText: text => ({ text }),
})

const App = () => (
  <Provider store={externalStore}>
    <Subscribe to={externalStore}>{props => <div>{props.text}</div>}</Subscribe>
  </Provider>
)

Global setState

If you do not supply any functions in the object passed to createStore, a setState function would be added automatically for you. This applies to both createStore and the Provider above.

const store = createStore({ count: 0 })

const Test = subscribe(store)(props => (
  <button onClick={() => props.setState(state => ({ count: state.count + 1 }))}>
    {props.count}
  </button>
))

mapContextToProps

subscribe and Subscribe (the component) work with any React context, even polyfills. They pick providers and select state. Extend wrapped components from React.PureComponent and they will only render when picked state has changed.

// Subscribes to all contents of the provider
subscribe(context)
// Picking a variable from the store, the component will only render when it changes ...
subscribe(context, store => ({ loggedIn: store.loggedIn }))
// Picking a variable from the store using the components own props
subscribe(context, (store, props) => ({ user: store.users[props.id] }))
// Making store context available under the 'store' prop
subscribe(context, 'store')
// Selecting several providers
subscribe([Theme, Store], (theme, store) => ({ theme, store }))
// Selecting several providers using the components own props
subscribe([Theme, Store], (theme, store, props) => ({
  store,
  theme: theme.colors[props.id],
}))
// Making two providers available under the props 'theme' and 'store'
subscribe([Theme, Store], ['theme', 'store'])

If you like to provide context πŸš€

Examples: Global context | Transforms | Unique context | Generic React Context

Contextual isn't limited to reading context and store patterns, it also helps you to create and share providers.

Custom providers & transforms

import { subscribe, moduleContext, transformContext } from 'react-contextual'

const Theme = moduleContext()(({ context, color, children }) => (
  <context.Provider value={{ color }} children={children} />
))

const Invert = transformContext(Theme)(({ context, color, children }) => (
  <context.Provider value={invert(color)} children={children} />
))

const Write = subscribe(Theme)(({ color, text }) => (
  <span style={{ color }}>{text}</span>
))

const App = () => (
  <Theme color="red">
    <Write text="hello" />
    <Invert>
      <Write text="world" />
    </Invert>
  </Theme>
)

With decorator

@moduleContext()
class Theme extends React.PureComponent {
  // ...
}

@transformContext(Theme)
class Invert extends React.PureComponent {
  // ...
}

@subscribe(Theme)
class Say extends React.PureComponent {
  // ...
}

API |Β Changelog | Pitfalls using context raw

More Repositories

1

react-springy-parallax

🌊 A springy, composable parallax-scroller for React - deprecated
JavaScript
1,328
star
2

mauerwerk

βš’ A react-spring driven masonry-like grid with enter/exit and shared element transitions
JavaScript
831
star
3

react-animated-tree

🌲Simple to use, configurable tree view with full support for drop-in animations
JavaScript
815
star
4

the-substance

Scroll, Refraction and Shader Effects in Three.js and React
JavaScript
371
star
5

poimandres-theme

⚫️ poimandres vsc theme
JavaScript
218
star
6

floating-shoe

JavaScript
171
star
7

immer-wieder

✨ React 16 context wrap with redux semantics powered by immer
JavaScript
167
star
8

learnwithjason

Learn how to use theejs in react using react-three-fiber πŸŽ‰
JavaScript
121
star
9

reactanoid

JavaScript
98
star
10

testlighting

JavaScript
93
star
11

scheduler-test

JavaScript
56
star
12

r3fv4

Created with CodeSandbox
JavaScript
34
star
13

r3f-aesop

JavaScript
21
star
14

nft-gallery

Created with CodeSandbox
JavaScript
17
star
15

react-higher-order

β˜”οΈ Maps render props to a higher order component
JavaScript
16
star
16

splats

TypeScript
15
star
17

untitled-game

Created with CodeSandbox
JavaScript
14
star
18

arc-x-pmndrs

JavaScript
12
star
19

projects

projects
JavaScript
7
star
20

react-spring-numerical

πŸ™Œ React-springs leaner doppelgΓ₯nger
JavaScript
7
star
21

awv3node-homepage

JavaScript
5
star
22

scroll-template

JavaScript
4
star
23

dom-resize

JavaScript
3
star
24

threeparcel

JavaScript
3
star
25

reacteurope

JavaScript
3
star
26

testsvg

2
star
27

plugs-draft

JavaScript
1
star
28

meshtransmissionmaterial

JavaScript
1
star
29

vite-three-js

JavaScript
1
star
30

zustand-website

CSS
1
star