0

There is a lot of guidance online about defining functions within React.Component objects, but I am having trouble finding best practices for functions within Functional Components. For instance, what are the implications of myFC_1 vs myMC_2 in the typescript code below.

interface Props { name: string};

export const myFC_1: FunctionComponent<Props> = (props:Props) {
    function helloWorld(): string {
        return "Hello " + props.name;
    }
    return <div> { helloWorld() }</div>
}

export const myFC_2: FunctionComponent<Props> = (props:Props) {
    const helloWorld =():string =>  {
        return "Hello " + props.name;
    } 
    return <div> { helloWorld() }</div>
}

2 Answers 2

1

Just be consistent every time you are doing this.. In functional component it doesn't really matter which approach u use. Fat arrow can be maybe a bit slower because of automatic binding which is useless in functional component, but I am literally just guessing without any benchmark :).

Class component is different thing.. When you are defining function inside render use fat arrow, so you don't have to think about context binding. So the main thing here is to just make deal with your team what you will use and then follow this rule.

Sign up to request clarification or add additional context in comments.

1 Comment

The performance may differ between engines but it is normally the same.
0

There's no best way, this is a matter of preference.

Function declaration can benefit from hoisting if necessary:

export const myFC_1: FunctionComponent<Props> = (props:Props) {
    return <div> { helloWorld() }</div>

    function helloWorld() {
        return "Hello " + props.name;
    }
}

And arrow function can be a one-liner:

export const myFC_2: FunctionComponent<Props> = (props:Props) {
    const helloWorld =() => "Hello " + props.name;

    return <div> { helloWorld() }</div>
}

string type is optional because it is inferred.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.