Martin Melichar
Martin Melichar

Reputation: 1156

In React, what is the difference between using functional component and just a function, which returns React node?

I just wonder if these two ways of processing code work the same.

For me it seems easier to just create a regular function, which returns React node. It can also return Array of React nodes, which can be easily built up during function call.

Is there a reason to pick one over another? It looks like hooks can be used in both too...

export function Sandbox () {

    return <>
        <FunctionComponent animalName={'dog'} />
        {renderFunction('dog')}
    </>;
};

function FunctionComponent (props:{animalName:string}) {

    return <div>
        {props.animalName}
    </div>

}

function renderFunction (animalName:string) {

    return <div>
        {animalName}
    </div>

}

Thanks for tips :)

Upvotes: 2

Views: 1207

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42170

In essence a function component already is just a function which returns a ReactNode. Note that the return type ReactNode actually does already allow for arrays as well as string, etc.

type ReactText = string | number;
type ReactChild = ReactElement | ReactText;

interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

The primary advantage of writing it as a function component is the ability to call the function using JSX syntax. You can also make use of nested JSX to automatically set the children prop on your function.

You don't need to use JSX. In your example it would be fine to call FunctionComponent({animalName: 'dog'}) (note: you cannot do this with class Components). In that case the primary difference between it and renderFunction('dog') is that one puts all of its arguments into a single props object and the other doesn't.

Upvotes: 2

Related Questions