SuperHi FM

Intro to Full Stack Javascript

Get access to Intro to Full Stack Javascript

  • Practical, go-at-your-own pace learning, with help from our industry experts and experienced teachers
  • Projects and code that you can alter and include in your own sites and portfolio
  • Resources to get you started and going post-course
Lesson 14

How does authentication work and what is PKCE?

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 🎉.

Private notes

A place for you to post notes about anything on this page. Only you can view your notes.

SuperHi FM

Want some ambient music in the background? Play our radio station!

Feeling stuck?

Don’t worry, we are here to help you with:

  • Speedy help from one of our team members
  • Detailed, relevant solutions
  • Direct access to peer support through Discord!

Remember, there’s no such thing as a silly question, so don’t hesitate to reach out, we love hearing from you!