Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I pass props as arguments to functions within components?

When I write a function - a helper function for example - inside a component and want to use the value of one of the component's props within this function, should I pass the prop as an argument to the function or access it directly? What might affect this decision? I've always passed the props as arguments but am not sure if this is introducing needless complexity.

I.e. which of the following is best:

function MyComponent({number}){
    function numberPlusOne(){
        return number + 1;
    }

    return(
        <h1>{numberPlusOne()}</h1>
    )
}

or

function MyComponent({number}){
    function numberPlusOne(number){
        return number + 1;
    }

    return(
        <h1>{numberPlusOne(number)}</h1>
    )
}
like image 400
Sylith Avatar asked Dec 15 '25 06:12

Sylith


2 Answers

In a functional component, your props are guaranteed to be up-to-date in each render, so I think calling the function with the prop is not more "correct" than using the prop directly inside the function, in terms of the value's correctness and performance.

There are a couple of things to consider though:

  • If you use the prop directly inside the function, it makes it more tightly coupled with your component, making it hard to separate it later. But, if it shouldn't be tightly coupled, it should be defined elsewhere in the first place, so...
  • If you use the function with the argument, you'd better rename the parameter to prevent variable shadowing, so it's an unnecessary complexity added.

So, all in all, I think it's totally okay to use the prop directly (and recommended) and if you want to make the function reusable by passing the props as arguments, define it elsewhere in the first place (in utils/ folder, for example).

like image 65
technophyle Avatar answered Dec 16 '25 20:12

technophyle


It's better to pass the prop as an argument to the function. Then, you could pull the function up and out of the component and even into a separate file. This also sets you up nicely for unit testing.

Learn more by reading up on "pure functions".

like image 43
user1160006 Avatar answered Dec 16 '25 22:12

user1160006



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!