skip to Main Content

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>
    )
}

2

Answers


  1. 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".

    Login or Signup to reply.
  2. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search