Quickly and easily create react-context and implement state management

You can find the full documentation at https://react-component-shell.js.org

react component shell is a package that allows you to quickly and easily create react-context and apply state management,

oysters There is a JavaScript class which has some methods and properties to provide some kind of functionality to the project.

main concept is to create shell object and connect them to react components.

installation

npm install react-component-shell
enter fullscreen mode

exit fullscreen mode

basic use

let’s make one Play Shell which has two methods: run() And stop() who updates .paused property of State,

game.js

import {Shell} from 'react-component-shell'

class Game extends Shell {
   state = { paused: true }

   run() {
      this.updateState(state => {
          return {...state, paused: false}
      })
   }

   stop() {
      this.updateState(state => {
          return {...state, paused: true}
      })
   }
}

export {Game}
enter fullscreen mode

exit fullscreen mode

let’s use now createShellProvider() Serves to create a react-context provider and access hook for the game shell.

game-context.js

import {createShellProvider} from 'react-component-shell'
import {Game} from './game.js'

const [ GameProvider, useGame, useGameState ] = createShellProvider({ shellClass: Game })

export {GameProvider, useGame, useGameState}
enter fullscreen mode

exit fullscreen mode

createShellProvider() The function returns an array with three values. The first value is a provider component, the second value is a react hook that returns a shell object, and the last value is a react hook that returns a state value by a selector.

In our example, we created GameProvider provider and useGame, useGameState hook

Now let’s use them in React app.

app.js

import {GameProvider, useGame, useGameState} from './game-context.js'

const App = (props) => {
    return (
        <GameProvider>
            <GamePauseButton />
        </GameProvider>
    )
}

const GamePauseButton = (props) => {
    const game = useGame()
    const paused = useGameState(state => state.paused)

    const clickHandler = () => {
        if (paused) {
            game.run()
        } else {
            game.stop()
        }
    }

    return <button onClick={clickHandler}>{ paused ? 'Run' : 'Stop' }</button>

}

export default App
enter fullscreen mode

exit fullscreen mode

In the above example, we can apply useGame() either useGameState() hook for any component inside <GameProvider>,

useGame() Returns a Game object, and we can call its methods run() either stop() Or read and write its properties.

useGameState(selector) Returns the value of the game position, represented by selector function, and each time a change of the specified value in the state will result in re-rendering of the given component.

Link

Leave a Comment