React JS Custom Hook

A hook just returns state and optionally a function that can mutate that state.

  1. Define the hook, here my hook is reading a token from sessionStorage and if it exists then set this as the initial state.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { useState } from 'react';

export default function useToken() {
const getToken = () => {
const tokenString = sessionStorage.getItem('token');
const userToken = JSON.parse(tokenString);
return userToken?.token;
};
const [token, setToken] = useState(getToken());
const saveToken = (userToken) => {
sessionStorage.setItem('token', JSON.stringify(userToken));
setToken(userToken.token);
};

return {
setToken: saveToken,
token,
};
}
  1. Import and destruct the response from the hook
1
2
3
4
import useToken from './useToken';

const App = () => {
const { token, setToken } = useToken();
  1. Set the token value where response came from a fetch
1
setToken(response);

Note that this is consuming the whole response, we could just pass in response.token

For context the complete reponse could like the below where token is a valid JWT

1
2
3
4
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiJkMTEwNGQ1MC0yN2NlLTQwZDEtYjc5OS1mZTA4MDczOTU4NzUiLCJuYmYiOjE2NTA5NDY0ODksImV4cCI6MTY1MTU1MTI4OSwiaWF0IjoxNjUwOTQ2NDg5LCJpc3MiOiJwb3JreS5pbyIsImF1ZCI6ImJmZi5wb3JreS5pbyJ9.-30-p-2baW2XCFAd1YAaPVRPHNc-qibkxIfO9JOIt-I",
"displayName": "Porky"
}

References