I am curious why React does not define the components like the following instead. It has to be invoked the component and its returned value for the first time and to re-render the only thing that needs to be done is invoke the returned value which is a function as well. The functions that do not need props would be defined in the outer function scope and the ones that do would be defined in the inner function scope.
function Component(){
const [count, setCount] = useState(0)
//other states
const incerement = () =>{
setState((oldState) => oldState 1)
}
// define other functions that do not need props but does state here
return (props) => {
//define the functions that need props here
return (
<div>{count}</div>
<button onClick={increment}>Increment</button>
)
}
}
CodePudding user response:
Good question.
The most obvious drawback here is the lack of subsequent calls to useState. Calling it not only sets the default value on first call but also retrieves current value on each next call.
In your current proposal, the inner scope is supposed to somehow obtain current value of the state but there seems to be no way of how it would be possible.
Anyway, it doesn't seem clear what your proposal would improve. It's still a function React calls. However, the drawback of your approach is obvious: on the first call, React would have to call the upper level function and the inner function afterwards and then call only inner function on subsequent calls. This would mean React would have to handle the first call differently than subsequent calls.
What React does currently, however, is it calls components in the very same way, regardless of the distinction between the first and all other calls.