I'm new to JavaScript and React.
I was reading from React's documentation https://reactjs.org/docs/hooks-reference.html#functional-updates
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
And was curious how different function signatures are being handled in setState (here setCount
) function returned by React.useState
.
Since JavaScript is a dynamically typed language and therefore function overloading does not exist, my initial guess was that there's only a single function that simulates the behavior of function overloading, such as in this question Function overloading in Javascript - Best practices.
Or is this handled in some different way by React?
EDIT: I think this question could be also applied to the React.useState
function itself https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});