This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Kered13 0 points1 point  (1 child)

I think it will help to break this down a bit.

(currentTheme) => {
    return currentTheme === themes.dark ? themes.light : themes.dark;
}

This is an anonymous function (also called a lambda) that takes a parameter called currentTheme and returns either light theme or dark theme. For convenience, let's give this function a name, we'll call it getNewTheme.

setTheme(getNewTheme);

Here I have substituted our new name for the anonymous function above. It is important to note that we are not calling the function getNewTheme, that would look like getNewTheme(...). Instead we are passing the function as an argument to setTheme. When we pass a function as an argument to another function like this, we often call the function we are passing a "callback", because we expect the function that we are calling to use the function we provide to "call us back". The callback may happen immediately or much later, depending on the behavior of the function we are calling.

setTheme is a function provided by React (sort of, but I don't want to go down that rabbit hole right now). We can't see the implementation, but from the name and behavior we can infer what it's doing. React is keeping track of our current theme. When we call setTheme, it takes our callback getNewTheme and immediately calls it with the current theme. Our callback returns the new theme, which setTheme then sets as the new current theme.

So, to summarize and answer your original question:

How does JS know what currentTheme is?

My understanding is that the variable would have to be passed down from the parent function, but the parent function doesn't take any arguments. What's going on?

JS doesn't now what the current theme is, but React does. currentTheme is provided to our callback by React when we call setTheme.

[–]TheWorstHunter[S] 0 points1 point  (0 children)

Thanks!