When following best practices in React, what is the best way to share functions across components? A simple example I have right now is a date formatter that just takes a DateTime and converts it to a string with a static (for now) format of YYY-MM-DD
The structure of my code is as follows:
1. mainComponent.tsx
a. tableOne.tsx
b. tableTwo.tsx
c. timeline.tsx
Each .tsx file has a corresponding useState. Here's what I have thought of so far. Should I:
Maybe there's another option I'm missing? But so far I've been doing a lot of 1 & 3.
Thanks!
Maybe there's another option I'm missing? But so far I've been doing a lot of 1 & 3.
Following the 1st
option you will end up with circular dependency since you will have to import the child component and from the child component you will have to import the function from parent. However if it's about passing it as props, it's still problematic since you will have to memoize it in case if you don't want any excessive re-renders.
Personally I'd go with the 3rd
option, but only if you are going to use the mentioned function inside MainComponent
. If you'd decide to use it also somewhere else, would be best to create a separate directory in the main root, e.g. utils
with dateUtils.ts
file to store all of the helper functions related with Date.