This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

React best practices and patterns to reduce code – Part 3


That is third the article about React finest practices, When you have not learn my earlier articles, please test them out.



React finest practices and patterns to cut back code – Half 1


React finest practices and patterns to cut back code – Half 2

let us take a look at some extra finest practices and patterns to cut back code.




Retailer Tokens to an HTTP Cookie quite than localStorage


Unhealthy code:
const token = localStorage.getItem("token");
if (token) {
  axios.defaults.headers.frequent["Authorization"] = token;
}
Enter fullscreen mode

Exit fullscreen mode



Good code:
import Cookies from "js-cookie"; //  use one other library if you'd like

const token = Cookies.get("token");
if (token) {
  axios.defaults.headers.frequent["Authorization"] = token;
}
Enter fullscreen mode

Exit fullscreen mode



Higher code:
No Code πŸ˜‰
Enter fullscreen mode

Exit fullscreen mode

Be aware:

  • Cookies are shared with all websites on the identical area. No must move the token to each request. If the backend shouldn’t be on the identical area because the frontend, it’s a must to use 2nd method.
  • Use the HttpOnly attribute for to stop entry to cookie values(token) by way of JavaScript. however you want some flag at React app for checking route entry.



Use interceptors for auth token or another frequent headers


Unhealthy code:
axios.get("/api", {
  headers: {
    ts: new Date().getTime(),
  },
});
Enter fullscreen mode

Exit fullscreen mode



Good code:
// solely as soon as
axios.interceptors.request.use(
  (config) => {
    // Do one thing earlier than request is distributed
    config.headers["ts"] = new Date().getTime();
    return config;
  },
  (error) => {
    // Do one thing with request error
    return Promise.reject(error);
  }
);

// Element
axios.get("/api");
Enter fullscreen mode

Exit fullscreen mode




Use context/redux for passing props to kids


Unhealthy code:
const auth = { title: "John", age: 30 };
return (
  <Router>
    <Route path="/" component={<App auth={auth} />} />
    <Route path="/dwelling" component={<Dwelling auth={auth} />} />
  </Router>
);
Enter fullscreen mode

Exit fullscreen mode



Good code:
return (
  <Supplier retailer={retailer}>
    <Router>
      <Route
        path="/"
        component={<App />}
      />
      <Route
        path="/dwelling"
        component={<Dwelling />}
      />
    </Router>
);


// Inside youngster element
const { auth } = useContext(AuthContext); // For context
const { auth } = useSelector((state) => state.auth); // For redux
Enter fullscreen mode

Exit fullscreen mode




Use helper perform for styled-components


Not dangerous code however tough to learn while you suppose when it comes to px.
const Button = styled.button`
  margin: 1.31rem 1.43rem;
  padding: 1.25rem 1.5rem;
`;
Enter fullscreen mode

Exit fullscreen mode



Create helper perform for px to rem conversion
const toRem = (worth) => `${worth / 16}rem`;
const Button = styled.button`
  margin: ${toRem(21)} ${toRem(23)};
  padding: ${toRem(20)} ${toRem(24)};
`;
Enter fullscreen mode

Exit fullscreen mode




Use frequent perform for enter knowledge change


Unhealthy code:
const onNameChange = (e) => setName(e.goal.worth);
const onEmailChange = (e) => setEmail(e.goal.worth);

return (
  <kind>
    <enter kind="textual content" title="title" onChange={onNameChange} />
    <enter kind="textual content" title="e mail" onChange={onEmailChange} />
  </kind>
);
Enter fullscreen mode

Exit fullscreen mode



Good code:
const onInputChange = (e) => {
  const { title, worth } = e.goal;
  setFormData((prevState) => ({
    ...prevState,
    [name]: worth,
  }));
};

return (
  <kind>
    <enter kind="textual content" title="title" onChange={onInputChange} />
    <enter kind="textual content" title="e mail" onChange={onInputChange} />
  </kind>
);
Enter fullscreen mode

Exit fullscreen mode




Use intersection observer for lazy loading


Unhealthy code:
component.addEventListener("scroll", perform (e) {
  // do one thing
});
Enter fullscreen mode

Exit fullscreen mode



Good code:
const useScroll = (ele, choices = {}): boolean => {
  const [isIntersecting, setIsIntersecting] = useState(false);
  useEffect(() => {
    const cb = (entry) => setIsIntersecting(() => entry.isIntersecting);
    const callback: IntersectionObserverCallback = (entries) => entries.forEach(cb);
    const observer = new IntersectionObserver(callback, choices);
    if (ele) observer.observe(ele);
    return (): void => ele && observer.unobserve(ele);
  }, [ele]);
  return isIntersecting;
};


// Element
const ref = useRef<any>();
const isIntersecting = useScroll(ref?.present);

useEffect(() => {
  if (isIntersecting) {
    // name an API
  }
}, [isIntersecting]);

Enter fullscreen mode

Exit fullscreen mode




Use HOC for authentication and personal route


Unhealthy code:
const Element = () => {
  if (!isAuthenticated()) {
    return <Redirect to="/login" />;
  }
  return <div></div>;
};
Enter fullscreen mode

Exit fullscreen mode



Good code:
const withAuth = (Element) => {
  return (props) => {
    if (!isAuthenticated()) {
      return <Redirect to="/login" />;
    }
    return <Element {...props} />;
  };
};

// Route
<Route path="/dwelling" element={withAuth(Dwelling)} />;

// Element
const Element = (props) => <div></div>;
export default withAuth(Element);
Enter fullscreen mode

Exit fullscreen mode




Use Array of route object to outline the routes


Frequent method:
return (
  <Router>
    <Route path="/" component={<App />} />
    <Route path="/about" component={<About />} />
    <Route path="/subjects" component={<Matters />} />
  </Router>
);
Enter fullscreen mode

Exit fullscreen mode



Good code:
const routes = [
  {
    path: "/",
    role: ["ADMIN"],
    component: React.lazy(() => import("../pages/App")),
    kids: [
      {
        path: "/child",
        element: React.lazy(() => import("../pages/Child")),
      },
    ],
  },
  {
    path: "/about",
    function: [],
    component: React.lazy(() => import("../pages/About")),
  },
  {
    path: "/subjects",
    function: ["User"],
    component: React.lazy(() => import("../pages/Matters")),
  },
];

const createRoute = ({ component, kids, function, ...route }) => {
  const Element = function.size > 0 ? withAuth(component) : component;
  return (
    <Route key={route.path} {...route} component={<Element />}>
      {kids && kids.map(createRoute)}
    </Route>
  );
};

return <Routes>{routes.map(createRoute)}</Routes>;
Enter fullscreen mode

Exit fullscreen mode

Be aware: This requires extra code, however it’s extra versatile. If you wish to use extra HOC, it’s a must to solely replace createRoute.




Use Typescript


Nothing mistaken should you do not use Typescript πŸ˜€, however it’ll provide help to to put in writing higher code
npx create-react-app my-app --template typescript
Enter fullscreen mode

Exit fullscreen mode




Use eslint, prettier for Formatting
npm set up -D eslint prettier
npx eslint --init
Enter fullscreen mode

Exit fullscreen mode



Refer this: Eslint setup, Prettier setup

πŸ˜₯ Not added full steps, I need to preserve this brief and easy. In the event you discover any difficulties, please go away a remark.




Use pre-commit hook to run eslint and prettier
npx mrm@2 lint-staged // It will set up and configure pre-commit hook

// This script might be created on the root of your undertaking
.husky/pre-commit

// Bundle.json
"lint-staged": {
  "src/**/*.{js,ts,jsx,tsx}": [
    "npm run lint",
    "npm run prettier",
    "npm run unit-test",
    "git add"
  ]
}
Enter fullscreen mode

Exit fullscreen mode

Be aware:

  • You’ll be able to replace the config to run prettier and eslint on commit. You’ll be able to add or take away the command within the undertaking package deal.json.
  • Higher to have CI & CD setup for this, Somebody can remark out the pre-commit hook and push code to git.



Use vscode extension for higher improvement


Auto Close Tag, Auto Rename Tag, CodeMetrics, CSS Peek, ES7+ React/Redux/React-Native snippets, Eslint, GitLens, Import Cost, Prettier

Be aware: Should attempt code complexity extension(CodeMetrics). It’s going to provide help to to put in writing higher code by displaying the complexity of your code.

React best practices and patterns to reduce code - Part 3


Thanks for studying 😊

Obtained any questions or further? please go away a remark.



Should Learn If you have not


React finest practices and patterns to cut back code – Half 1


React finest practices and patterns to cut back code – Half 2


3 steps to create state administration library with React Hooks and Context API


Javascript brief reusable features trick and ideas



Extra content material at style-tricks.com.


Comply with me on Github, Twitter, LinkedIn, Medium, and Stackblitz.



The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?