DEV Community

Cover image for React Custom Hooks (useFluidFont)
sundarbadagala
sundarbadagala

Posted on

React Custom Hooks (useFluidFont)

INTRO ๐Ÿ””

Hello World! ๐Ÿ‘‹
Today we are discussing another custom hook๐Ÿช named useFluidFont๐Ÿ”ฅ. In this post, we will discuss this hook usage, code and use case.

USAGE ๐Ÿ””

As a front-end developer ๐Ÿ˜Ž, I know responsive designs are crucial in web development. Changing font size based on screen size is the main important thing in responsive design. Usually, we use media queries in CSS ๐ŸŽจ to achieve this. However, it leads to lengthy code and multiple media queries for different screen sizes ๐Ÿ™. But, by using the useFluidFont๐Ÿ”ฅ custom hook, we can achieve the same output with efficient code practice ๐Ÿ˜Š.

WITH MEDIA QUERIES ๐Ÿ”•

.container {
    font-size: 24px;
}

@media screen and (max-width:1280px) {
    .container {
        font-size: 22px;
    }
}

@media screen and (max-width:1140px) {
    .container {
        font-size: 20px;
    }
}

@media screen and (max-width:980px) {
    .container {
        font-size: 18px;
    }
}

@media screen and (max-width:720px) {
    .container {
        font-size: 16px;
    }
}
Enter fullscreen mode Exit fullscreen mode

WITH CUSTOM HOOK ๐Ÿ””

๐Ÿ“Œ NOTE: before creating this hook, we need to create another hook named useWinowResize๐Ÿš€. It is already created on our custom hook series. Please check ๐Ÿ‘‰๐Ÿป useWindowResize

import { useCallback } from "react";
import { useWindowResize } from "./useWindowResize";

export const useFluidFont = () => {
  const { width } = useWindowSize();
  const getFont = useCallback(
    (minFont, minWidth, maxFont, maxWidth) => {
      if (width <= minWidth) {
        return minFont;
      } else if (width >= maxWidth) {
        return maxFont;
      } else {
        return `calc(${minFont}px + (${maxFont} - ${minFont}) * ((100vw - ${minWidth}px) / (${maxWidth} - ${minWidth})))`;
      }
    },
    [width]
  );
  return getFont;
};

Enter fullscreen mode Exit fullscreen mode

USE CASE ๐Ÿ””

import React from "react";
import "./styles.css";
import { useFluidFont } from "./useFluidFont";

function App() {
  const font = useFluidFont();
  return (
    <div>
      <div className="container">HELLO WORLD</div>
      <div style={{ fontSize: font(16, 720, 24, 1280) }}>HELLO WORLD</div>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

CONCLUSION ๐Ÿ””

By using the above hook, we can change the font size of application responsively without using multiple CSS media queries.

I hope you people like the useFluidFont hook. We will meet with another hook in another post.

Peace ๐Ÿ™‚

Top comments (0)