There are tons of resources out on the web which explain what closure is...
I will cut the crap of giving this:
a function inside a function bla bla... is closure.
Instead what I will do is to give you a 1 minute snippet that you need to scan and understand the output of the below 👇 code will be (without running on compiler or looking into the answer).
Once done we can check the answer and learn the concept of it.
Please feel free to comment, would love to respond and learn together.
let cachedFunc = null
function log(message) {
if (!cachedFunc) {
// creates a function that closes over `message`
// keep in mind `message` inside `log` is different
// on each call
cachedFunc = () => console.log(message)
}
cachedFunc();
}
log("hello")
log("goodbye")
Check the answer below compare:
Click to expand the Answer
Step by step execution:
cachedFuncis declared withnull, and a functionlog.On calling
log("hello"), the context of callinglogfunction is same as thecachedFuncdeclared, so it will find it's value tonullas declared in outer scope.Inside the
if conditionit will update thecachedFuncto a inline function which prints argumentmessageto console.Then it calls
cachedFuncmethod which results in the message "hello".-
On the second call
log("goodbye")will not initialize the method again.So it will call the method that was in previous scope, in which the value of
messageis "hello" and that's why it will print the same "hello" again.
Further explanation related to Reactjs:
Under the hood, useCallback works in a very similar way. On the first render, React saves the function you pass to useCallback somewhere and will always return that function.
Every other render will have your saved function, and will "remember" the scope it was created in, including the old value.
Without useCallback or adding dependencies to it, a new function would be created on each render or change in the dependencies, which means it would be able to refer to new with an up-to-date value.
Here is the link to codepen to further play with it :)
Regards.
Top comments (0)