Home > Mobile >  Reuse component used in different context in react
Reuse component used in different context in react

Time:06-15

I have a component which is using state & action from a context. In a different part of my app, I've created a different context but i want to reuse the same component. Can you please suggest any standard/elegant way to do so ?

import React from 'react'

const Sidebar = () => {
  const {state, action} = useDashboard();
  return (
    <div>...</div>
  )
}

export default Sidebar

Now i want to use this:

    const Sidebar = () => {
      const {state, action} = usePlotter();
      return (
        <div>...</div>
      )
    }
    
    export default Sidebar

useDashboard, usePlotter are hooks providing useContext().

CodePudding user response:

Move condition logic to inside another hook:

const useDashboardOrPlotter = (condition: boolean) => {
  const {stateDashboard, actionDashboard} = useDashboard();
  const {statePlotter, actionPlotter} = usePlotter();

  return condition ? {stateDashboard, actionDashboard} : {statePlotter, actionPlotter}
}

const Sidebar = () => {
  ... condition
  const {state, action} = useDashboardOrPlotter(condition);
  return (
    <div>...</div>
  )
}

CodePudding user response:

You can use like this in same component.

const {state: plottState, action: plottAction} = usePlotter();
const {state: dashboardState, action: dashboardAction} = useDashboard();

now use plottState, plottAction, dashboardState, dashboardAction

  • Related