What really goes on under the hood with authentication? And what is PKCE?
Debugging tip:
A quick note on useEffect
because it often trips people up (it even trips me up sometimes): if you’re having trouble with API requests in this lesson, remember to check the dependency array of your useEffect
function.
In React, if you don’t add an empty dependency array (at the very least) then a useEffect function will run over and over again.
So let’s say we created this useEffect
to run our getToken
function:
useEffect(() => {
getToken()
})
The getToken
function will take our token and use it in an API request. This function will be called by useEffect whenever useEffect runs. When making API requests with tokens, what will then happen is the first time the API request will succeed, the token will expire, and any subsequent attempts to use the same token will fail.
But how often are will this useEffect run if we write it like this? An infinite number of times…
So the second time it runs and calls getToken? The third time? The nth time? They will all fail because that token can’t be used a 2, 3 or n-number of times.
Instead, our useEffect function should look like this:
useEffect(() => {
getToken()
}, [])
That comma and empty array makes all the difference.
A useEffect dependency array is basically a list of things that useEffect is waiting on - if they change in anyway it’s useEffect’s signal to run again. If it’s empty, then useEffect will run once and only once. That’s what we want when we’re dealing with tokenised API calls.
With the added , []
useEffect will only run once, the token will only be used once, and the code will succeed 🎉.