Question on components and props in React

So, I’m really trying to grasp how to organize my code in React.

In my head the best practice would to be to try and keep everything local and within the component that makes sense. However, you run into issues where multiple components will need access to something, let’s say a function for example.

Is it then best practice to just keep it in the App component and pass it down through props? For example, a cartCount set to 0 on an ecommerce app that increases by 1 every time you add something to the cart. The cartCount would be held in a header component so the user can see how many items are in his/her cart. but the actual function would be needed in a card component where the products are all listed, and the function would need access to the cartCount to work.

I’m sorry if that’s a bit confusing but would you have to keep everything in a higher up parent component so that you can pass everything down where it’s needed? I don’t know of any other ways of doing this. My first instinct would tell me to just put that kind of data in the App component since it’s the MAIN component and then just pass things down as needed. I feel like the App component would be very weird to look at and hard to read eventually though.

If I a have standalone functions that are used in multiple components which are more than likely in multiple separate files, I will typically create a util.js file that contains all such files and import the relevant functions needed into the other component file and main app file.

I assume you are talking about state setters and not just utility functions?

  1. Collocate state to the component that needs it. If no other components need the state let the component handle its own state.

  2. Have state in the closest common parent to the components that need the state and pass it down to the components. You do not have to lift the state up higher than needed but the higher you lift it up the easier it may be to have new components use the state (without having to refactor) but you get more prop drilling.

  3. Use context and/or a state management lib (zustand for example).