react-context-selector
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

react-context-selector

This small package will help us to clean react context unwanted re-renders using a selector hook

NPM

Install

npm install --save react-context-selector

Usage

we should import createContextSelector from react-context-selector to create a Cleanner component that should be mounted directly under the context provider and a selector hook to use instead of the standard React.useContext

import React, { createContext } from 'react'
import { createContextSelector } from 'react-context-selector'

// first we define the context
export const CONTEXT = createContext(undefined as State)
// then we create the cleanner/selector package
export const [Cleanner, useContextSelector] = createContextSelector(CONTEXT)

the Cleanner component should be mounted directly under the Provider and before all other components in the context tree

import React, { createContext } from 'react'
import { Cleanner, CONTEXT } from './configs'

const { Provider } = CONTEXT

const ProviderTest = () => {
  return (
    <Provider value={state}>
      <Cleanner />
      {/*then we can mount our consummer components*/}
      {props.children}
    </Provider>
  )
}

now we can use the useContextSelector hook in some consummer components

import React, { createContext } from 'react'
import { useContextSelector } from './configs'

const ConsummerTest = () => {
  // this conponent will re-render only if value1 changes
  const value1 = useContextSelector((state) => {
    // do something with the context state and return whatever you want
    return doSomething(state)
  })
}

check a working example here

see also

License

MIT © https://github.com/fernandoem88/react-context-selector

Package Sidebar

Install

npm i react-context-selector

Weekly Downloads

15

Version

1.0.3

License

MIT

Unpacked Size

27.4 kB

Total Files

15

Last publish

Collaborators

  • fernando.ekutsu