Search code examples
reactjstypescriptreact-hooksfrontendrefactoring

React - best practices on sharing functions across components


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:

  1. add the function directly to mainComponent.tsx and pass the function in to the relevant components that need it
  2. have a useState specifically for a dateFormatter that the functions that need it can pull as necessary (note that I have run into bugs before where if I update the function and the function is both in the parent & child components, the child component won't rerender with the correct state)
  3. Have another file on the mainComponent.tsx level that is specific a dateFormatter.tsx and have the components use it as a global static function.

Maybe there's another option I'm missing? But so far I've been doing a lot of 1 & 3.

Thanks!


Solution

  • 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.