Lucas
Lucas

Reputation: 12

Sharing data with child components without props

I'm sharing data with child components like the code below.

const App = () => {
  const [appData, setAppData] = useState({});

  const dealId = new URLSearchParams(window.location.search).get('dealId');

  useEffect(() => {
    /* API Call here */,
        (response) => {
          setAppData(
            Object.entries(response).reduce((previousValue, currentValue) => {
              return {
                ...previousValue,
                [currentValue[0]]: currentValue[1].data(),
              };
            }, {})
          );
        }
      );
    }
  }, [dealId]);

  return (
    <React.Fragment>
      <CSSBaseline />
      <NavAppBar dealId={dealId} user={appData.user} />
      <Panel>
        <Contact
          contact={appData.contact}
          contactFields={appData.contactFields}
        />
        <Event event={appData.event} />
        <Accommodation
          packageItemFields={appData.packageItemFields}
          packageItems={appData.packageItems}
          hotels={appData.hotels}
        />
        <Course courses={appData.courses} event={appData.event} />
        <Transportation transportationFields={appData.transportationFields} />
      </Panel>
    </React.Fragment>
  );
};

export default App;

This feels like not a good pattern since I need to pass the same data more than one time to different components. Is there any way to improve on this? Using context would be more suitable?

Upvotes: 0

Views: 61

Answers (1)

Ntshembo Hlongwane
Ntshembo Hlongwane

Reputation: 1051

Rule of thumb that will help you in deciding when is the right time to add state management like Context api or Redux that I use is when I see myself prop drilling heavy now I then turn to using Context Api.

Ask yourself the following questions below before even deciding between Context or Redux

When should I use Context Api?

Ans: If you are using Redux only to avoid passing props down to deeply nested components, then you could replace Redux with the Context API

So when should I use Redux?

Ans: Redux is a state container, handling your application's logic outside of your components, putting your entire app state in one container, using Redux DevTools to track when, where, why, and how your application's state changed, or using plugins such as Redux Saga,Redux Persist, etc.

In This case you can use Redux.

So now if you keep this ideas in mind then you will choose wisely

Upvotes: 2

Related Questions