Borrus-sudo / unplugin-add-deps

Takes care of maintaining your dependencies array for (p)react hooks!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

unplugin-add-deps

Automatically constructs the dependencies hook array for your (p)react hooks based on the dependencies used in the callback!

All Contributors License Last Commit Stars Forks

๐ŸŽฉ Features

  • Available as a ready-to-use vite, rollup, esbuild, webpack or a babel plugin!
  • Constructs [] hooks at build time automatically!

๐Ÿ’ฝ Installation

pnpm i unplugin-add-deps

๐Ÿ”ฎ Usage

import { vite, rollup, webpack, babel, esbuild } from "unplugin-add-deps";

//vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { vite } from "unplugin-add-deps";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vite(), react()],
});

โ‰ FAQ

  • Q. How to prevent adding deps to hooks?

    A. By using a leading comment to the hook /*ignore*/

    /*ignore*/ useEffect(() => {}, []);
  • Q. Why does it not add deps to hook without the leading comment?

    A. It is necessary to pass the blank deps array to the hook. This also prevents from ts getting mad at you!

    let [count, setCount] = useState(0);
    useEffect(() => {
      console.log(count);
    }, []);
    //  โ†“ โ†“ โ†“ โ†“ โ†“ โ†“ โ†“ โ†“
    let [count, setCount] = useState(0);
    useEffect(() => {
      console.log(count);
    }, [count]);
  • Q. How about props?

    A. It is necessary to follow the destructure pattern for the props for the plugin to pick those as deps

    // Right way โœ…
    function App({ hello }) {
      useEffect(() => {
        console.log(hello);
      }, []);
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
          </header>
        </div>
      );
    }
    //  โ†“ โ†“ โ†“ โ†“ โ†“ โ†“ โ†“ โ†“
    function App({ hello }) {
      useEffect(() => {
        console.log(hello);
      }, [hello]);
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
          </header>
        </div>
      );
    }
    
    /* Wrong Way โŽ*/
    function App(props) {
      useEffect(() => {
        console.log(props.hello);
      }, []);
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
          </header>
        </div>
      );
    }

๐ŸŽ‰ Contributing

Contributions are welcome! Whether it is a small documentation change or a breaking feature, we welcome it!

Please note: All contributions are taken under the MIT license

๐Ÿ‘ฅ Contributors

About

Takes care of maintaining your dependencies array for (p)react hooks!

License:MIT License


Languages

Language:TypeScript 71.5%Language:CSS 16.0%Language:HTML 6.0%Language:JavaScript 4.4%Language:Shell 2.1%