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
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".
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:
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).