Skip to content

πŸ”₯In this package, I have developed complete hooks and useful functions for you to do your projects more easily, quickly and accurately

License

Notifications You must be signed in to change notification settings

mohammad-zolghadr/react-hooks-plus

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

38 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Β  Β  install size Β  NPM Downloads

Increasing speed and accuracy is one of the main criteria for cleaner and better coding

πŸ“ž Who I am and how to communicate with me

Table of Content

  • Installation And Conditions
  • Functions
    Hooks

    Installation And Conditions ↑

    You can use :

    npm i react-hooks-plus

    or

    yarn add react-hooks-plus


    Random Functions ↑

    randomNumber ↑

    First you need to import

    import { randomNumber } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    console.log(randomNumber());

    By doing this, a random number (max 4 digits) will appear for you in the log


    randomNumberDigit ↑

    First you need to import

    import { randomNumberDigit } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    As the function parameter of the function, you must enter a number so that your final output is a number with the desired number of digits

    console.log(randomNumberDigit(7));

    In this example, your log output will be a 7-digit random number


    randomNumberRange ↑

    First you need to import

    import { randomNumberRange } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    As the function parameter of the function, you must enter two numbers as min and max so that your final output is a number in your desired range.

    console.log(randomNumberRange(1, 100));

    In this example, your log output will be a random number between 1 and 100


    randomNumberEven ↑

    First you need to import

    import { randomNumberEven } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    As the function parameter of the function, you must enter a boolean value and two numbers as min and max. If the first parameter is true, it means your output is an even number and if it is false, it means your output is an odd number. The second and third parameters are related to your determining the random number range

    console.log(randomNumberEven(true, 1, 100));

    In this example, your log output will be an even random number between 1 and 100


    randomString ↑

    First you need to import

    import { randomString } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    console.log(randomString());

    By doing this, a random string (max 5 char) will appear for you in the log


    randomStringLength ↑

    First you need to import

    import { randomStringLength } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    As an function parameter to the function, you must assign a number to it, which determines the length of your string

    console.log(randomStringLength(12));

    By doing this, your log output will be a random string of 12 characters long


    randomStringSymbols ↑

    First you need to import

    import { randomStringSymbols } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    console.log(randomStringSymbols());

    By doing this, a random string of letters, numbers and symbols (max 5 characters) will appear for you in the log.


    randomStringSymbolsLength ↑

    First you need to import

    import { randomStringSymbolsLength } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    As an function parameter to the function, you must assign a number to it, which determines the length of your string

    console.log(randomStringSymbolsLength(12));

    By doing this, your log output will be a random string of letters, numbers, and symbols that is 12 characters long


    Random Functions ↑

    convertToPersianNumber ↑

    This function converts English numbers to Persian or Arabic

    First you need to import

    import { convertToPersianNumber } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    //Example usage
    const input = '1234567890';
    const persianNum = convertToPersianNumber(input);
    console.log(persianNum); // "Ϋ±Ϋ²Ϋ³Ϋ΄Ϋ΅ΫΆΫ·ΫΈΫΉΫ°"

    convertToEnglishNumber ↑

    This function converts Persian or Arabic numbers to English

    First you need to import

    import { convertToEnglishNumber } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    //Example usage
    let PersianNum = 'Ϋ±Ϋ²Ϋ³Ϋ΄Ϋ΅';
    let engNum = convertToEnglishNumber(PersianNum);
    console.log(engNum); // output: 12345

    separateNumbers ↑

    This function separates the numbers three by three with ,

    First you need to import

    import { separateNumbers } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    //Example usage
    console.log(separateNumbers('1234567890')); // 1,234,567,890
    console.log(separateNumbers('Ϋ·Ϋ·Ϋ·Ϋ΅Ϋ²Ϋ²ΫΆ')); // Ϋ·,Ϋ·Ϋ·Ϋ΅,Ϋ²Ϋ²ΫΆ

    isPersianNumber ↑

    This function returns a Boolean value that indicates whether the number you sent as input to this function is Persian (Arabic) or not.

    First you need to import

    import { isPersianNumber } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    //Example usage
    console.log(isPersianNumber('Ϋ΅,Ϋ²Ϋ²ΫΆ')); // true
    console.log(isPersianNumber('Ϋ΅Ϋ²Ϋ²ΫΆ')); // true
    console.log(isPersianNumber(42735)); // false
    console.log(isPersianNumber('42,753')); // false

    Array Functions ↑

    UniqueArray ↑

    UniqueArray : Takes an array and returns a new array containing only unique elements.

    First you need to import

    import { uniqueArray } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const arr = [1, 2, 2, 3, 4, 4];
    const uniqueArr = uniqueArray(arr); // [1, 2, 3, 4]

    shuffleArray ↑

    shuffleArray : This function takes in an array and shuffles its contents randomly

    First you need to import

    import { shuffleArray } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const myArray = [1, 2, 3, 4, 5, 6];
    const shuffledArray = shuffleArray(myArray);

    chunk ↑

    chunk : This function takes an array and a chunk size and returns a new array with the original array split into chunks of the specified size

    First you need to import

    import { chunk } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const arr = [1, 2, 3, 4, 5, 6];
    const chunkedArr = chunk(arr, 3); // returns [[1, 2, 3], [4, 5, 6]]

    flattenArray ↑

    flattenArray : Takes an array of arrays and flattens it into a single array

    First you need to import

    import { flattenArray } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const arr = [[1, 2], [3, 4], [5]];
    const flattenedArr = flattenArray(arr); // [1, 2, 3, 4, 5]

    findMaxIndex ↑

    The findMaxIndex function takes an array of numbers as input and returns the index of the largest element in the array.

    First you need to import

    import { findMaxIndex } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const arr1 = [3, 7, 1, 9, 4];
    const maxIndex = findMaxIndex(arr1);
    console.log(
      `The largest element in arr1 is ${arr1[maxIndex]} at index ${maxIndex}.`
    );

    isArrayEmpty ↑

    isArrayEmpty : Function to check if an array is empty

    First you need to import

    import { isArrayEmpty } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const myArr = [4, 6, 8, 5];
    console.log(isArrayEmpty(myArr)); // false

    getMaxElement ↑

    getMaxElement : Function to get the maximum element in an array

    First you need to import

    import { getMaxElement } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const arr: number[] = [10, 5, 20, 15];
    console.log(getMaxElement(arr)); // Output: 20

    getMinElement ↑

    getMinElement : Function to get the minimum element in an array

    First you need to import

    import { getMinElement } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const arr: number[] = [10, 5, 20, 15];
    console.log(getMinElement(arr)); // Output: 5

    hasElement ↑

    hasElement : Function to check if an array contains a specific element or not First you need to import

    import { hasElement } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const fruits: string[] = ['apple', 'banana', 'orange'];
    console.log(hasElement(fruits, 'banana')); // Output: true

    sum ↑

    sum : This function returns the sum of all the elements in the input array.

    First you need to import

    import { sum } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const total = sum(numbers);
    console.log(`The sum is ${total}`); //output: 15

    average ↑

    average : Returns the average value of the elements of the array

    First you need to import

    import { average } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const arr = [2, 4, 6, 8, 10];
    const avg = average(arr); // returns 6

    addElementToArrayIfNotExist ↑

    addElementToArrayIfNotExist : Function to add an element to an array if it doesn't exist in the array.

    First you need to import

    import { addElementToArrayIfNotExist } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    let newArr = addElementToArrayIfNotExist(oldArr, elementToAdd);

    addObjectToArrayIfPropNotExist ↑

    addObjectToArrayIfPropNotExist : Function to add an object to an array if a specific property of that object doesn't exist in the array.

    First you need to import

    import { addObjectToArrayIfPropNotExist } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    let newArr = addObjectToArrayIfPropNotExist(oldArr, objToAdd, 'propertyName');

    removeElement ↑

    removeElement : Function to remove a specific element from an array

    First you need to import

    import { removeElement } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    let numbers: number[] = [10, 20, 30, 40];
    numbers = removeElement(numbers, 20);
    console.log(numbers); // Output: [10, 30, 40]

    removeDuplicatesByProperty ↑

    First you need to import

    removeDuplicatesByProperty : This function takes an array of objects and in the second parameter of the function, it takes a key and checks if there were objects in this array that had the same key, it removes all duplicate items.

    import { removeDuplicatesByProperty } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const people = [
      { id: 1, name: 'John', age: 30 },
      { id: 2, name: 'Jane', age: 25 },
      { id: 3, name: 'John', age: 30 },
      { id: 4, name: 'Bob', age: 40 },
      { id: 5, name: 'Jane', age: 20 },
    ];
    
    const uniquePeople = removeDuplicatesByProperty(people, 'name');
    console.log(uniquePeople);
    /* Output:
    [
      { id: 1, name: "John", age: 30 },
      { id: 2, name: "Jane", age: 25 },
      { id: 4, name: "Bob", age:40 }
    ];
    */

    sortByProperty ↑

    sortByProperty: Takes an array of objects and a property name and returns a new array sorted by the values of that property.

    First you need to import

    import { sortByProperty } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    const users = [
      { name: 'John', age: 25 },
      { name: 'Mary', age: 20 },
      { name: 'Adam', age: 30 },
    ];
    
    const sortedUsers = sortByProperty(users, 'age'); // [{ name: 'Mary', age: 20 }, { name: 'John', age: 25 }, { name: 'Adam', age: 30 }]

    sortArrayDesc ↑

    sortArrayDesc : Function to sort an array in descending order.

    First you need to import

    import { sortArrayDesc } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    let newArr = sortArrayDesc(oldArr);

    sortArrayAsc ↑

    sortArrayAsc : Function to sort an array in ascending order.

    First you need to import

    import { sortArrayAsc } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    let newArr = sortArrayAsc(oldArr);

    Local Storage ↑

    First you need to import

    import { saveToLocalStorage, getFromLocalStorage } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    In the saveToLocalStorage function, you must enter the key as the first function parameter, and in the second parameter, you must enter the value that you want to save in the browser storage.

    In the getFromLocalStorage tab, you must enter the key value as an function parameter to return the value stored by this key from the browser's storage.

    // save to local
    const myFunction = () => {
      saveToLocalStorage('MY-KEY', 'MY-VALUE');
    };
    
    // get from local
    console.log(getFromLocalStorage('MY-KEY'));

    By doing this, you save the MY-VALUE value in the browser's memory with the MY-KEY key

    And in the log, you will receive the information stored with the MY-KEY key from the browser's storage


    Decimal With Precision ↑

    First you need to import

    import { setPrecisionForDecimal } from 'react-hooks-plus';

    And then to use it, proceed as follows :

    You can limit the number of digits of a decimal number by using the setPrecisionForDecimal function

    1. The first parameter is your number, which can be a decimal number or an integer
    2. The second parameter is the number of decimal digits.
    setPrecisionForDecimal(3.14159, 2); // Output: 3.14
    setPrecisionForDecimal(3, 2); // Output: 3
    setPrecisionForDecimal(3.14159, 0); // Output: 3
    setPrecisionForDecimal(3.1485, 2); // Output: 3.15

    useCopyToClipboard ↑

    First you need to import

    import { useCopyToClipboard } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    copyToClipboard is a function that you must enter a value that you want to save to the clipboard as the input of this function.

    copied is a boolean value that returns true when the content is saved to the clipboard and returns false after 1.5 seconds. copied is used when you want to put a successful text in the relevant subfield to show the user that the content in question has been successfully saved to the clipboard.

    Example :

    function MyComponent() {
      const { copied, copyToClipboard } = useCopyToClipboard();
    
      return (
        <div>
          <button onClick={() => copyToClipboard('Some text to copy to clipboard')}>
            Copy to clipboard
          </button>
          {copied && <p>Text copied to clipboard!</p>}
        </div>
      );
    }
    export default MyComponent;

    useLocalStorage ↑

    First you need to import

    import { useLocalStorage } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    The first parameter of the useLocalStorage hook is the key that your value can be obtained in the browser storage with this key, and the second parameter is your value.

    You should store the return value from the useLocalStorage hook as a useState. That is, a value and a setValue And you can use this value, which is a react state, wherever you want Also, using the setValue function, you can change the value wherever you want, and this value change will also be done in the local storage.

    Example :

    function PhoneNumberInput() {
      const [phoneNumber, setPhoneNumber] = useLocalStorage('phoneNumber', '');
    
      const handlePhoneNumberChange = (event) => {
        setPhoneNumber(event.target.value);
      };
    
      return (
        <input type='tel' value={phoneNumber} onChange={handlePhoneNumberChange} />
      );
    }

    useDocTitle ↑

    First you need to import

    import { useDocTitle } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    It takes a string as input parameter

    const MyComponent = () => {
      useDocTitle('My Component Title');
    
      return (
        <div>
          <h1>My Component</h1>
        </div>
      );
    };

    useOnClickOutside ↑

    First you need to import

    import { useOnClickOutside } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    This hook takes a ref as the first parameter and a function as the second parameter So you have to assign this ref to an element on the page and create a function. This way, the function will be called every time outside of your element is clicked

    Example :

    import { useRef } from 'react';
    import useOnClickOutside from 'react-hooks-plus';
    
    function App() {
      const ref = useRef(null);
    
      const handleClickOutside = () => {
        console.log('Clicked outside!');
      };
    
      useOnClickOutside(ref, handleClickOutside);
    
      return (
        <div ref={ref}>
          <p>Click outside this element and check the console!</p>
        </div>
      );
    }

    useHover ↑

    First you need to import

    import { useHover } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    To use this hook, you should note that it has two return values The first value is a ref, which you must assign to the target element And the second return value is a boolean whose value becomes true whenever hover is performed on your element for which you have defined ref.

    Example :

    import useHover from 'react-hooks-plus';
    
    function MyComponent() {
      const [ref, isHovered] = useHover();
    
      return (
        <div ref={ref}>
          <p>{isHovered ? 'Hovered!' : 'Not Hovered'}</p>
        </div>
      );
    }

    useFetch ↑

    First you need to import

    import { useFetch } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    The useFetch hook takes the url of an API as an input parameter and gives you three return values

    1. One of the return values ​​is isLoading, which is a Boolean value and from the time the request is sent, until the response is received from the API side, its value is true, and when the response is received (whether it encounters an error or data) are received safely, its value will be false
    2. Another return value is error, which returns an error if there is an error
    3. And another return value is data, which contains the fetched data from the API (the response from the API)

    Example :

    import { useFetch } from 'react-hooks-plus';
    
    function MyComponent() {
      const { data, isLoading, error } = useFetch('/api/data');
    
      if (isLoading) {
        return <div>Loading...</div>;
      }
    
      if (error) {
        return <div>Error: {error.message}</div>;
      }
    
      return (
        <div>
          <h1>{data?.title}</h1>
          <div>{data?.body}</div>
        </div>
      );
    }

    useMedia ↑

    First you need to import

    import { useMedia } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    useMedia(queries: string[], values: T[], defaultValue: T)

    1. Queries must be an array of CSS media queries (e.g. ['(max-width: 768px)', '(orientation: landscape)']).
    2. Values must be an array of any type, corresponding to the queries (e.g. [true, 'large']).
    3. DefaultValue is the value returned when none of the media queries match (e.g. false).

    The hook returns the current value, based on the current screen size.

    Example :

    import React from 'react';
    import useMedia from 'react-hooks-plus';
    
    function App() {
      const isMobile = useMedia(['(max-width: 767px)'], [true], false);
    
      return (
        <div>
          <h1>You are browsing on {isMobile ? 'mobile' : 'desktop'}</h1>
        </div>
      );
    }

    useScroll ↑

    First you need to import

    import { useScroll } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    The useScroll hook returns two states x and y

    Both states, as their name suggests, indicate the amount that has been scrolled from the page

    Example :

    import useScroll from 'react-hooks-plus';
    
    const MyComponent = () => {
      const { x, y } = useScroll();
    
      return (
        <div>
          <p>Current scroll position:</p>
          <p>X: {x}</p>
          <p>Y: {y}</p>
        </div>
      );
    };

    useScreen ↑

    First you need to import

    import { useScreen } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    The useScreen hook returns two states width and height

    Both states, as their name suggests, show the current size of width and height

    Example :

    import { useScreen } from 'react-hooks-plus';
    
    const MyComponent = () => {
      const { width, height } = useScreen();
    
      return (
        <div>
          My screen dimensions are {width}px x {height}px
        </div>
      );
    };

    useOnScreen ↑

    First you need to import

    import { useOnScreen } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    The useOnScreen hook receives a ref as an input parameter and returns a boolean value

    If this boolean value is true, that is, the element for which we considered the ref value, will be seen in the viewport that is exposed to the user.

    If its value is false, it may be due to scrolling or..., this element is at the bottom or top of the page and the user does not see it in the viewport.

    Example :

    import { useRef } from 'react';
    import useOnScreen from 'react-hooks-plus';
    
    function MyComponent() {
      const ref = useRef(null);
      const isOnScreen = useOnScreen(ref);
    
      return (
        <div ref={ref}>
          {isOnScreen ? 'Visible on screen' : 'Not visible on screen'}
        </div>
      );
    }

    Console Hooks ↑

    useConLog ↑

    First you need to import

    import { useConLog } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    The useConLog hook actually executes once every time the state changes and prints a message in console.log.

    You can enter as many values ​​as you want in its input parameter

    In general, this hook for debugging will greatly speed up your work

    Example :

    import useConLog from 'react-hooks-plus';
    
    function MyComponent() {
      const [count, setCount] = useState(0);
    
      useConLog('Count is : ', count);
    
      return (
        <div>
          <p>{count}</p>
          <button onClick={() => setCount(count + 1)}>Increase count</button>
        </div>
      );
    }

    useConGroup ↑

    First you need to import

    import { useConGroup } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    The useConGroup hook actually creates a group in your console and displays your content as a collapse You can easily print your contents grouped in the console

    The first parameter of this hook is your Content or State Your second parameter is the label of the group, this part is optional and You can leave this field blank

    In general, this hook for debugging will greatly speed up your work

    Example :

    import useConsoleGroup from 'react-hooks-plus';
    
    const MyComponent = () => {
      const data = { name: 'John', age: 27 };
    
      useConsoleGroup(data, 'User Data');
    
      // rest of your component code
    };

    useConTable ↑

    First you need to import

    import { useConTable } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    You can use the useConTable hook to log a table of our data to the console every time it changes

    1. The data parameter (First Parameter) is an array of values ​​that you want to print in the log
    2. The columns parameter (Second Parameter) is an array of strings representing the properties of the objects you want to display in the table.

    In general, this hook for debugging will greatly speed up your work

    Example :

    import React, { useState } from 'react';
    import useConTable from 'react-hooks-plus';
    
    function App() {
      const [data, setData] = useState([
        { id: 1, name: 'Alice', age: 25 },
        { id: 2, name: 'Bob', age: 30 },
        { id: 3, name: 'Charlie', age: 35 },
      ]);
    
      useConTable(data, ['name', 'age']);
    
      // rest of your code
    }
    
    export default App;

    useConTime ↑

    First you need to import

    import { useConTime } from 'react-hooks-plus';

    Then, you can use this hook in your component like this:

    The useConTime hook returns two functions: startConsole and endConsole. You can call startConsole at the beginning of the operation you want to measure, and call endConsole when the operation is complete. The hook prints the time taken to the console in milliseconds.

    You can assign the input parameter to useConTime and you can leave it blank. This input parameter, which must be a string, displays the text inside the console before the time. If your text is empty, the default text is this : Time Taken: 136ms

    In general, this hook for debugging will greatly speed up your work

    Example :

    import React from 'react';
    import useConTime from 'react-hooks-plus';
    
    const MyComponent = () => {
      const { startConsole, endConsole } = useConTime();
    
      const handleClick = () => {
        startConsole();
        // do some heavy calculations or API calls here
        endConsole();
      };
    
      return <button onClick={handleClick}>Click me</button>;
    };
    
    export default MyComponent;

    πŸ“ž Who I am and how to communicate with me ↑

    I am a Freelance Frontend Web Developer with patience and creativity and caring for projects. I am ready to cooperate with the latest technologies such as React.js and TailwindCss to build a stylish website with the best UX.


    The current version of react-hooks-plus includes the functions and hooks that were tested and presented in the initial version

    If you find any ideas, suggestions, problems or bugs, please let me know

    The main forum for free and community support is the project Issues on GitHub

    πŸ”Ό Released on : April/2023 - Mohammad Zolghadr