Skip to content

Commit

Permalink
refactor(front): merge state to useDynStyle
Browse files Browse the repository at this point in the history
  • Loading branch information
SARDONYX-sard committed Oct 6, 2023
1 parent 4d310e9 commit d0aeca3
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 11 deletions.
7 changes: 3 additions & 4 deletions frontend/src/components/pages/converter.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
"use client";

import { Toaster } from "react-hot-toast";
import { useDynStyle, useStorageState, useToastLimit } from "@/hooks";
import { ConvertForm } from "@/components/form";
import { useDynStyle, useToastLimit } from "@/hooks";
import { Box } from "@mui/material";
import { Toaster } from "react-hot-toast";

export default function Converter() {
useToastLimit(1);
const [style, _setStyle] = useStorageState("customCSS");
useDynStyle(style);
useDynStyle();

return (
<>
Expand Down
5 changes: 2 additions & 3 deletions frontend/src/components/pages/settings.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
"use client";

import { Box, Button, TextField } from "@mui/material";
import { useDynStyle, useStorageState } from "@/hooks";
import { useDynStyle } from "@/hooks";

export default function Settings() {
const [style, setStyle] = useStorageState("customCSS");
useDynStyle(style);
const [style, setStyle] = useDynStyle();

return (
<Box
Expand Down
12 changes: 8 additions & 4 deletions frontend/src/hooks/dyn_style.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import { useInsertionEffect } from "react";
import { useStorageState } from "@/hooks";

/**
* Inject CSS dynamically on the client side.
* # NOTE
* Frequent style recalculation is inevitable,
* but this hook can solve the delay problem caused by style injection lifecycle discrepancies.
* - See: [useInsertionEffect](https://react.dev/reference/react/useInsertionEffect)
* @param css
*/
export function useDynStyle(css: string) {
export function useDynStyle() {
const [style, setStyle] = useStorageState("customCSS");

useInsertionEffect(() => {
const styleElement = document.createElement("style");
styleElement.innerHTML = css;
styleElement.innerHTML = style;
document.head.appendChild(styleElement);
return () => {
document.head.removeChild(styleElement);
};
}, [css]);
}, [style]);

return [style, setStyle] as const;
}

0 comments on commit d0aeca3

Please sign in to comment.