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:
On calling Inside the Then it calls On the second call So it will call the method that was in previous scope, in which the value of Under the hood, Every other render will have your saved function, and will "remember" the scope it was created in, including the old value. Without Click to expand the Answer
Step by step execution:
cachedFunc
is declared with null
, and a function log
.log("hello")
, the context of calling log
function is same as the cachedFunc
declared, so it will find it's value to null
as declared in outer scope.if condition
it will update the cachedFunc
to a inline function which prints argument message
to console.cachedFunc
method which results in the message "hello".log("goodbye")
will not initialize the method again.
message
is "hello" and that's why it will print the same "hello" again.
Further explanation related to
Reactjs
:
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.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)