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)