Member-only story

React best practices and patterns to reduce code — Part 3

Rahul Sharma (DevsMitra)
5 min readMar 21, 2022

--

React best practices and patterns to reduce code | Rahul Sharma(DevsMitra)

This is 3rd the article about React best practices, If you have not read my previous articles, please check them out.

React best practices and patterns to reduce code — Part 1
React best practices and patterns to reduce code — Part 2

let’s look at some more best practices and patterns to reduce code.

Store Tokens to an HTTP Cookie rather than localStorage

Bad code:

const token = localStorage.getItem("token");
if (token) {
axios.defaults.headers.common["Authorization"] = token;
}

Good code:

import Cookies from "js-cookie"; //  use another library if you wantconst token = Cookies.get("token");
if (token) {
axios.defaults.headers.common["Authorization"] = token;
}

Better code:

No Code 😉

Note:

  • Cookies are shared with all sites on the same domain. No need to pass the token to every request. If the backend is not on the same domain as the frontend, you have to use 2nd approach.
  • Use the HttpOnly attribute to prevent access to cookie values(token) via JavaScript. but you need some flags at React app for checking route access.

Use interceptors for auth token or any other common headers

Bad code:

axios.get("/api", {
headers: {
ts: new Date().getTime(),
},
});

Good code:

// only once
axios.interceptors.request.use(
(config) => {
// Do something before request is sent
config.headers["ts"] = new Date().getTime();
return config;
},
(error) => {
// Do something with request error
return Promise.reject(error);
}
);
// Component
axios.get("/api");

--

--

Rahul Sharma (DevsMitra)
Rahul Sharma (DevsMitra)

Written by Rahul Sharma (DevsMitra)

I’m a technology enthusiast who does web development. Passionate to contribute to open-source projects and make cool products.

No responses yet