Home > Back-end >  Understanding JSX in React
Understanding JSX in React

Time:07-09

So I get whats going on but I also dont get whats going on. What I mean is this, I got the code below (see below code) from the react website and I am going through the process of understanding react and how to use it properly. So my question is this, why are the variables "firstName" and "lastName" declared outside the scope of the function they will be used in? like wouldn't be easier to declare the variables in the very scope of the function?

function formatName(user) {
  return user.firstName   ' '   user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

CodePudding user response:

I see two possibilities:

  1. formatName is a helper function that's potentially called multiple times, with different data. If that's the case, then you can't define the data inside the function, since it will be different each time. If this is the scenario we're in, then i think the code you showed makes sense.

  2. formatName is called exactly once, so the data is always the same. In that case, i agree you could put the data inside the function. But at that point, you could also just delete the function and calculate the formatted name inline. Keeping it as a one-time-use function would only be useful if it helps with readability.

CodePudding user response:

When the user variable is declared outside the function, the data can be changed elsewhere, and the function doesn't need to know how to get the data — it just need to know the values of the data.

CodePudding user response:

as I know, if we declare a function/variable inside function component, it will create new function/object every render, let say we use a component inside loop process, it will affect memory of the user browser. so create a function that do something outside function component is best practice.

  • Related