DEV Community

Azizi Yazit
Azizi Yazit

Posted on

Create module in React

There is no module been defined in React and its known that React give full control on the code structure to the developers.

module

module can be use to make the code structure better. In React, I like to create a module as a Provider. This is because provider is the one who supply the props, callbacks and data to its consumers (children).

module as provider

const ModuleAContext = createContext({})
const initialState = { stateA: '', stateB: false, stateC: {}}

function ModuleA (props) {
 const [providerState, dispatch] = useReducer(reducer, initialState)
 const moduleAContextValue = {...props, providerState, dispatch}

 function reducer (state, action) {
  switch (action.type) {
   case STATE_A_CHANGED: 
    return { ...state, stateA: action.stateA }
   case STATE_B_CHANGED: 
    return { ...state, stateB: action.stateB }
   case STATE_C_CHANGED: 
    return { ...state, stateB: action.stateC }
   default: 
    return initialState
  }
 }

 return (
  <ModuleAContext.Provider value={moduleAContextValue}>
   <ChildA />
   <ChildB />
   <ChildC />
  </ModuleAContext.Provider>
 )

}

As provider, moduleA is not only responsible for supplying the data and the callback but also manage events that happened in its children (dispatch).

create module children as a consumers

function ChildA () {
 const moduleAContext = useContext(ModuleAContext)

 function handleClick (a) {
  dispatch({type: STATE_A_CHANGED, stateA: a })
 }

 return (
  <div onClick={handleClick}>{moduleAContext.stateA}</div>
 )
}

function ChildB () {
 const moduleAContext = useContext(ModuleAContext)

 function handleClick (b) {
  dispatch({type: STATE_B_CHANGED, stateB: b })
 }

 return (
  <div onClick={handleClick}>{moduleAContext.stateB}</div>
 )
}

function ChildC () {
 const moduleAContext = useContext(ModuleAContext)

 function handleClick (c) {
  dispatch({type: STATE_C_CHANGED, stateC: c })
 }


 return (
  <div onClick={handleClick}>{moduleAContext.stateC}</div>
 )
}

The Consumers is a components that been used by the module. They communicate thru context of the module (ModuleAContext).

summary

We have using Context API and use provider-consumers pattern to expose the module props, module state and callbacks to its children (consumers). Adding module in code system helps developer to design complex component as mixture of component that's live under one module.

next series

We will talk about "Creating page in React" where page is Container that contains many modules. And we will use custom hooks for modules communication.

Discussion (0)