Search code examples
reactjstypescript

What's the difference between a React.FunctionComponent and just a function?


Using TypeScript I usually define my own components using syntax like this:

// define an Options element and a viewOptions property

type OptionsProps = {
  viewOptions: ViewOptions;
};
export const Options: React.FunctionComponent<OptionsProps> = (props: OptionsProps) => {
  const {viewOptions} = props;
  // CODE here to render elements using viewOptions
}

My question, could I systematically use this instead?

// do the same as a simple arrow function

export const Options = (viewOptions: ViewOptions): JSX.Element => {
  // CODE here to render elements using viewOptions
}

I guess the only difference is in how they're invoked:

  • <Options viewOptions={viewOptions}/> -- an element
  • {Options(viewOptions)} -- a function call

Is there any other difference

  • In usability? Even the latter syntax seems to be a "React Function", from the top of which I can invoke (use) a hook.
  • Or in behaviour -- e.g. in whether something is re-rendered if the argument changes?

Solution

  • The obvious difference in that example is that you have different parameter types, props is not the same type as viewOptions. The more direct equivalent would be:

    export const Options = ({viewOptions}: OptionsProps): JSX.Element => {
      // CODE here to render elements using viewOptions
    }
    

    And this is the same function, but without some of the explicit typing. You can remove even more:

    export const Options = ({viewOptions}: OptionsProps) => {
      // CODE here to render elements using viewOptions
    }
    

    Those two versions are instances of React.FunctionComponent<OptionsProps>, they are just not explicit about it.