DEV Community

Azizi Yazit
Azizi Yazit

Posted on

Create Page in React

Page

Page can be defined as a Container of the modules. Page is the closest common ancestor for its modules (container children).

One of the important technique when creating a page is Lifting State Up. And the reason why we are not using Context API in the Page is because we want to limit the re-rendering on the page level.

When the nearest above the component updates, this Hook (useContext) will trigger a rerender with the latest context value passed to that MyContext provider.
(React docs)

You can refer the "Create Module in React" article here

Page as closest common ancestor of moduleA and moduleB

function PageA() {
 const [stateA, setStateA] = useState('')
 const [stateB, setStateB] = useState('')

 return (
  <div>
   <moduleA setStateA={setStateA} stateB={stateB} />
   <moduleB setStateB={setStateB} stateA={stateA} />
  </div>
 )

}

moduleA

function moduleA(props) {
 const { setStateA, stateB } = props
 const moduleAContextValue = {setStateA, stateB}

 return (
  <ModuleAContext.Provider value={moduleAContextValue}>
   <componentA1 />
   <componentA2 />
  </ModuleAContext.Provider>
 )

}

moduleB

function moduleB(props) {
 const { setStateB, stateA } = props
 const moduleBContextValue = {setStateB, stateA}

 return (
  <ModuleBContext.Provider value={moduleBContextValue}>
   <componentB1 />
   <componentB2 />
  </ModuleBContext.Provider>
 )

}

component might look like this

function componentA1() {
  const moduleAContext = useContext(ModuleAContext)
  const { stateB, setStateA } = moduleAContext

  function handleClick() {
   setStateA('state A')
  }

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

}

The Page state and Module context can be illustrated like below:

Page manage the communication between modules using technique called Lifting state up. While Module manage the communication between components using Context API (createContext & useContext) and useReducer.

next series

On the next article, we will discuss on managing communication between pages and the "page communication manager" is either Redux, Router or Custom Hook.

code

All the code sample can be viewed here Codesandbox

Top comments (0)