React Custom Hooks: useLocalStorage - Simply Explained!

Поділитися
Вставка
  • Опубліковано 28 вер 2023
  • Join The Discord! → discord.cosdensolutions.io
    Source Code → github.com/cosdensolutions/co...
    In this video we will learn about custom React hooks, starting with useLocalStorage. This is a very useful hook that allows you to easily interact with the local storage in React. We'll create a React custom hook that will allow us to set items in the local storage, retrieve them, and remove them from the local storage. This React hook will be highly re-usable and can be used in any component!

КОМЕНТАРІ • 62

  • @malekabdelkader9250
    @malekabdelkader9250 9 місяців тому +10

    We have Unspoken rule in some organizations: a custom hook should use another hook.
    Anything else might violate the React Rules of Hooks. These rules ensure that hooks are called in the same order on every render and that they are not conditionally called. Violating these rules can lead to unexpected behavior in your components.
    With respect, thank you for your videos 🫡

    • @krzysztofkwolek5810
      @krzysztofkwolek5810 6 місяців тому +4

      Plus if you want to reuse it with different key, you would have to multiply your functions, rename them, etc. What’s in the video is an example of something that shouldn’t be a custom hook, just exported function. They are also reusable.

  • @OleksandrKaminiev
    @OleksandrKaminiev 8 місяців тому +1

    Nice explanation. Thank you!

  • @mohamed-zhioua
    @mohamed-zhioua 9 місяців тому +2

    great job as always , by the way i have done the first try to contribute in a open source by improving the useLocalStorage Hook to Handle Multiple Keys

  • @user-ob9qm4br2j
    @user-ob9qm4br2j 3 місяці тому

    Brother your teaching technique daymmm🤯

  • @learnearn8721
    @learnearn8721 8 місяців тому +1

    Your tutorial are really helpful thanks a lot 🙏🙏🙏🙏🙏🙏🙏

  • @eddnufc93
    @eddnufc93 8 місяців тому +7

    Rather than return an object containing { getItem, setItem, removeItem }. If you had returned them as an array [ get, set, clear ] you could then name them in the aame way as you would using useState. You could also use the hook several times in the same component like so.
    const [getName, setName, clearName] = useLocalStorage('name')
    const [getAge, setAge, clearAge] = useLocalStorage('age')
    You could still rename them with aliasing, but its not so nice
    const { getItem: getName, setItem: setName, removeItem: clearName } = useLocalStorage('name')
    const { getItem: getAge, setItem: setAge, removeItem: clearAge } = useLocalStorage('age')

    • @cosdensolutions
      @cosdensolutions  8 місяців тому +1

      I still favor the object returning because I like aliasing things that way. With arrays you can very easily mix up the order. But ideally, you'd actually make the key part of the functions, so you would only need one hook!

  • @andrea_zero
    @andrea_zero 9 місяців тому

    Very useful!! Thanks

  • @ALi-Sloom
    @ALi-Sloom 7 місяців тому

    Mann , You're Amazing

  • @imammaulana6707
    @imammaulana6707 2 місяці тому

    You save my day bro 🤩

  • @abrahamorherhe2434
    @abrahamorherhe2434 8 місяців тому

    Thanks for your videos.

  • @ravisankarp61
    @ravisankarp61 9 місяців тому

    I love this video , thank you.

    • @ravisankarp61
      @ravisankarp61 8 місяців тому

      Do u have a course , I would like to check it if it is in my budget :)

  • @Mroskas
    @Mroskas 9 місяців тому +7

    I think a simple and good addition would be to convert get function to generic. Because now we might as well use jsx. 😁

  • @BradySie-wo6vf
    @BradySie-wo6vf 9 місяців тому +19

    It doesn’t need to be a hook just a regular function will do

    • @cosdensolutions
      @cosdensolutions  9 місяців тому +3

      better a hook, to re-use it easily and also allow it to have state or other hooks inside

    • @ivankraev4264
      @ivankraev4264 9 місяців тому +6

      And what if you want to mutate more than one key ? You should call the hook again? Isnt it better if the functions receive key and value ?

  • @beb316ratnesh2
    @beb316ratnesh2 2 місяці тому

    Nice Explanation! The only problem: Did not explained what custom hooks are, their purpose, use cases etc. Not an ideal choice for a beginner.

  • @osmar6150
    @osmar6150 7 місяців тому

    You are the best

  • @alvinacosta2312
    @alvinacosta2312 8 місяців тому +3

    i think you need to use hooks inside the custom hook for it to be a custom hook? i think this is just a function, a helper function maybe? good video just the same :)

    • @cosdensolutions
      @cosdensolutions  8 місяців тому +1

      not necessarily. This is designed to be a custom hook, even without state. Doing it this way makes it super easy to add state later on or callbacks. If you did it in a helper function, you'd have to convert it to a hook later on anws if you wanted those things

    • @alvinacosta2312
      @alvinacosta2312 8 місяців тому

      @@cosdensolutions great great! Thanks for the reply!

    • @haciendadad
      @haciendadad 7 місяців тому

      it is not a requirement to use a React Hook inside a custom hook. Custom hooks can be used to encapsulate any type of logic, including stateful logic, imperative logic, and even other custom hooks. However, it is common to use React Hooks inside of custom hooks in order to reuse stateful logic across multiple components.

  • @sachinmalik5837
    @sachinmalik5837 9 місяців тому

    Haha, I like how you always kinda make way for subscribe message right there in code.

  • @bmielki
    @bmielki 8 місяців тому +1

    is there a reason that you used the key as a parameter of the hook and not to the functions inside instead?

    • @cosdensolutions
      @cosdensolutions  8 місяців тому +1

      so you didn't have to always pass the key to every function

  • @einfacherkerl3279
    @einfacherkerl3279 7 місяців тому

    shouldn't this be done inside useEffect in useLocalStorage?

  • @fetyagency9808
    @fetyagency9808 6 місяців тому

    why indexedDB and the libraries wrapped around it, is subtlety used among the react community? i am really curios can somebody gimme an answer

  • @bronekjelonek3323
    @bronekjelonek3323 9 місяців тому

    Where do css class names like 'mb-2 text-3xl font-bold' come from? I'm quite new to react and they don't seem to be a bootstrap?

  • @user-qp6qu4xy1m
    @user-qp6qu4xy1m 8 місяців тому

    Interesting!
    Now tell me what is the use of this hook when we can straightaway use the built-in localStorage APIs?

    • @cosdensolutions
      @cosdensolutions  8 місяців тому

      It just makes it easier to handle the try catch blocks and exposes an easier api for it that is re-usable. You could also easily add additional logic to have state or effects in that hook

    • @user-qp6qu4xy1m
      @user-qp6qu4xy1m 8 місяців тому

      I don't find anything useful in the code presented until like you said, any additional logic or state implementation for realtime rendering of the localstorage data.
      const { getItem: getUserItem, setItem: setUserItem, removeItem: removeUserItem } = useLocalStorage('user');
      const { getItem: getTokenItem, setTokenItem, removeItem: removeTokenItem } = useLocalStorage('token');
      const somethingElse = useLocalStorage('something-else');
      somethingElse.getItem(); // ...
      somethingElse.setItem(); // ...
      somethingElse.removeItem(); // ...
      // VS
      localStorage.setItem('foo', 'value1');
      const foo = localStorage.getItem('foo');
      localStorage.removeItem('foo');
      try {
      localStorage.setItem('user', JSON.stringify(loggedInUser))
      } catch (error) {
      }
      Here built-in localStorage API looks much more easier to use and the useLocalStorage hook you suggested looks just a lot more complicated to use.
      Unless you add any advantages than the existing localStorage APIs, like, again, the use of states that maps to localStorage, which can then be used to show localStorage data live updating in the components, this hooks looks pretty unnecessary.
      @@cosdensolutions

  • @fabriziogiovannetti3020
    @fabriziogiovannetti3020 9 місяців тому

    The order of setItems, getItems and removeItems is different in the useLocalStorage declaration than its usage. It doesn’t matter?

  • @marcossequeira5433
    @marcossequeira5433 9 місяців тому

    Just for curious it's any clean way to detect changes in the local storage?

    • @cosdensolutions
      @cosdensolutions  9 місяців тому +1

      yeah, you can add an event listener to the 'storage' event to receive updates when things change!

    • @haciendadad
      @haciendadad 7 місяців тому

      @@cosdensolutions Also, you can use a useEffect hook

  • @TurkeyMaster
    @TurkeyMaster 9 місяців тому +1

    "Intersing! However, consider this scenario: what if I wish to have multiple useLocalStorage() instances within a single file? For instance, suppose I intend to manipulate data such as key: weather with values [rain, cloud, sun] and key: wind with values [n, e, s, w]. Wouldn't it be more elegant to employ a useLocalStorage() approach, where each returned function manages its own key:value pair, offering functions like setItem(key, val), deleteItem(key), and getItem(key)?"

    • @cosdensolutions
      @cosdensolutions  9 місяців тому +3

      yes, you could change the hook to accomodate that without a problem! This was specifically just for one key to keep it simple, but definitely !

  • @chun-lunlin7397
    @chun-lunlin7397 9 місяців тому

    that is not a hook but a simple util function, using use* prefix won't make it into a hook if it does not store any states.

  • @balduin_b4334
    @balduin_b4334 9 місяців тому +6

    Thats a good hook, but I don't know about setting the key when calling the hook.
    If you have multiple local storage items in one component you have to use the hook multiple times and then overwrite the function names.
    I think I would rather not set the key directly

    • @cosdensolutions
      @cosdensolutions  9 місяців тому +2

      yeah that can also work, you could also use the hook multiple times for different keys too, but yeah it's probably better to then make the changes to a hook that accommodates multiple keys

  • @ahmedfoda9823
    @ahmedfoda9823 8 місяців тому

    Hi, Sometimes when i delete data from local storage i still get it in the page unless i refreshed the browser, is there any reason for this behavior?

    • @cosdensolutions
      @cosdensolutions  8 місяців тому

      React doesn't by default check for changes in localStorage. As far as it's concerned, nothing changed so it doesn't need to re-render. That's why it works only on reload, because that's when React will render again

    • @ahmedfoda9823
      @ahmedfoda9823 7 місяців тому

      @@cosdensolutions Thanks, keep up the good work

  • @riadqerimi6701
    @riadqerimi6701 7 місяців тому

    Tell us about this copilot in vsco

    • @cosdensolutions
      @cosdensolutions  7 місяців тому

      have video on it! called my vscode setup

  • @oki7886
    @oki7886 9 місяців тому +9

    You made a hook without using any react hooks inside, kinda pointless to name it useLocalStorage, its just a normal function.

    • @cosdensolutions
      @cosdensolutions  9 місяців тому +3

      This video is kept simple, but if you were to add state or effects inside, this is much better as a hook

    • @quoccuong1733
      @quoccuong1733 9 місяців тому +2

      @@cosdensolutionsmaking it a hook just limits where it can be used. Make it a function then if theres a need for it to be a hook create one

    • @haciendadad
      @haciendadad 7 місяців тому

      Here are some examples of when you might want to use a custom hook without using any React Hooks inside of it:
      - To encapsulate imperative logic, such as making API calls or interacting with DOM elements.
      - To reuse a pattern or algorithm that doesn't involve state management.
      - To create a custom hook that is simply a wrapper for another function.

  • @hamedjafari5539
    @hamedjafari5539 9 місяців тому

    Why creating a custom hook when there is no hooks inside. I think you can simply create a util file and implement these as separate functions.

    • @cosdensolutions
      @cosdensolutions  9 місяців тому +2

      Because you would want to extend this further with some state and effects. This is just the simple version. This should always be a hook, helper functions are something else

    • @hamedjafari5539
      @hamedjafari5539 9 місяців тому

      Thanks for the answer@@cosdensolutions

  • @DioArsya
    @DioArsya 8 місяців тому

    its good, but it is only a normal function and not a hook 😢

    • @cosdensolutions
      @cosdensolutions  8 місяців тому

      this is the base version of it, you can add state and effects inside easily, that's the goal! This is a hook