Skip to content
Advertisement

Are there any benefits to defining functions within React components?

I brought the code below for easy understanding. Note the location of the a function.

There are declarative differences depending on where the a function is in React.
Both are code that works correctly.

Are there any benefits of defining them within React components?

function a(init, sub_name, value) {
  let t2 = cloneDeep(init);
  t2[sub_name] = value;
  return t2;
}

export default function test(props) {
  const [obj, setobj] = useState({
    first: { id: 123, v: 456 },
  });

  return (
    <div>
      <Test
        onUpdateData={(v) => setobj((p) => a(p, "first", v))}
      />
    </div>
  );
}
export default function test(props) {
  const [obj, setobj] = useState({
    first: { id: 123, v: 456 },
  });

  function a(init, sub_name, value) {
    let t2 = cloneDeep(init);
    t2[sub_name] = value;
    return t2;
  }

  return (
    <div>
      <Test
        onUpdateData={(v) => setobj((p) => a(p, "first", v))}
      />
    </div>
  );
}
  • This is a shortened code that makes it easy to understand the intent of the question.

Advertisement

Answer

In the first snippet you posted, the a function is essentially a private function in that file. It is used by your export but it is not accessible to other scopes.

In the second snippet, you have used a closure to encapsulate the a function, which is part of the exported function.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement