0

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.

2 Answers 2

2

This is a design decision that applies to JavaScript (and other languages) in general and not just ReactJS. The primary concern here is to ask if a() is used anywhere else or if it is just an implementation detail of test. If the later, then it is prefectly fine (and probably even preferred) to declare a() as a nested function. If you need to use a() in other components, then make it a global function instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thinking about the benefits you can get from the react life cycle perspective or grammar point of view, I asked the first question. I was missing the most basic one. Obviously, from a clean code perspective, I had to write code according to the purpose, but I was forgetting. Thank you.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.