React Custom Hooks: useLocalStorage - Simply Explained!

แชร์
ฝัง
  • เผยแพร่เมื่อ 3 ต.ค. 2024
  • 🚀 Project React → cosden.solutio...
    📥 Import React (Newsletter) → cosden.solutio...
    Join The Discord! → discord.cosden...
    Source Code → github.com/cos...
    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!

ความคิดเห็น • 63

  • @cosdensolutions
    @cosdensolutions  หลายเดือนก่อน

    Hope you enjoyed the video! I also have a really cool and unique course that will teach you way more than this video. You'll learn how to build an actual complex project with React. It's called "Project React" and you can find it at cosden.solutions/project-react. Also, I have a free weekly newsletter called "Import React" with tutorials, news, and cool stuff about React! You can sign up at cosden.solutions/newsletter?s=ytc

  • @mohamed-zhioua
    @mohamed-zhioua ปีที่แล้ว +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

  • @malekabdelkader9250
    @malekabdelkader9250 ปีที่แล้ว +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 9 หลายเดือนก่อน +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.

  • @Mroskas
    @Mroskas ปีที่แล้ว +7

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

  • @OleksandrKaminiev
    @OleksandrKaminiev 11 หลายเดือนก่อน +1

    Nice explanation. Thank you!

  • @DebrajRoy-x2c
    @DebrajRoy-x2c 6 หลายเดือนก่อน

    Brother your teaching technique daymmm🤯

  • @learnearn8721
    @learnearn8721 11 หลายเดือนก่อน +1

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

  • @eddnufc93
    @eddnufc93 11 หลายเดือนก่อน +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  11 หลายเดือนก่อน +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!

  • @imammaulana6707
    @imammaulana6707 5 หลายเดือนก่อน

    You save my day bro 🤩

  • @ALi-Sloom
    @ALi-Sloom 10 หลายเดือนก่อน

    Mann , You're Amazing

  • @naukaKontoTechniczne
    @naukaKontoTechniczne 3 หลายเดือนก่อน

    Great job!!! Thanks

  • @abrahamorherhe2434
    @abrahamorherhe2434 11 หลายเดือนก่อน

    Thanks for your videos.

  • @beb316ratnesh2
    @beb316ratnesh2 6 หลายเดือนก่อน

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

  • @ride.withzero
    @ride.withzero ปีที่แล้ว

    Very useful!! Thanks

  • @ravisankarp61
    @ravisankarp61 ปีที่แล้ว

    I love this video , thank you.

    • @ravisankarp61
      @ravisankarp61 ปีที่แล้ว

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

  • @alvinacosta2312
    @alvinacosta2312 ปีที่แล้ว +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  ปีที่แล้ว +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 ปีที่แล้ว

      @@cosdensolutions great great! Thanks for the reply!

    • @haciendadad
      @haciendadad 10 หลายเดือนก่อน

      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.

  • @osmar6150
    @osmar6150 10 หลายเดือนก่อน

    You are the best

  • @Hosain_Ahmed
    @Hosain_Ahmed 25 วันที่ผ่านมา

    In your code the key is static. isn't it?

  • @bmielki
    @bmielki 11 หลายเดือนก่อน +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  11 หลายเดือนก่อน +1

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

  • @sachinmalik5837
    @sachinmalik5837 ปีที่แล้ว

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

  • @JishnuRaj-q5f
    @JishnuRaj-q5f 11 หลายเดือนก่อน

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

    • @cosdensolutions
      @cosdensolutions  11 หลายเดือนก่อน

      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

    • @JishnuRaj-q5f
      @JishnuRaj-q5f 11 หลายเดือนก่อน

      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

  • @balduin_b4334
    @balduin_b4334 ปีที่แล้ว +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  ปีที่แล้ว +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

  • @fetyagency9808
    @fetyagency9808 9 หลายเดือนก่อน

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

  • @einfacherkerl3279
    @einfacherkerl3279 10 หลายเดือนก่อน

    shouldn't this be done inside useEffect in useLocalStorage?

  • @oki7886
    @oki7886 ปีที่แล้ว +9

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

    • @cosdensolutions
      @cosdensolutions  ปีที่แล้ว +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 ปีที่แล้ว +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 10 หลายเดือนก่อน

      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.

  • @TurkeyMaster
    @TurkeyMaster ปีที่แล้ว +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  ปีที่แล้ว +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 ปีที่แล้ว

    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.

  • @fabriziogiovannetti3020
    @fabriziogiovannetti3020 ปีที่แล้ว

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

  • @bronekjelonek3323
    @bronekjelonek3323 ปีที่แล้ว

    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?

  • @marcossequeira5433
    @marcossequeira5433 ปีที่แล้ว

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

    • @cosdensolutions
      @cosdensolutions  ปีที่แล้ว +1

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

    • @haciendadad
      @haciendadad 10 หลายเดือนก่อน

      @@cosdensolutions Also, you can use a useEffect hook

  • @riadqerimi6701
    @riadqerimi6701 10 หลายเดือนก่อน

    Tell us about this copilot in vsco

    • @cosdensolutions
      @cosdensolutions  10 หลายเดือนก่อน

      have video on it! called my vscode setup

  • @boogiecoin
    @boogiecoin หลายเดือนก่อน

    🥰

  • @hamedjafari5539
    @hamedjafari5539 ปีที่แล้ว

    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  ปีที่แล้ว +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 ปีที่แล้ว

      Thanks for the answer@@cosdensolutions

  • @ahmedfoda9823
    @ahmedfoda9823 11 หลายเดือนก่อน

    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  11 หลายเดือนก่อน

      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 11 หลายเดือนก่อน

      @@cosdensolutions Thanks, keep up the good work

  • @DioArsya
    @DioArsya 11 หลายเดือนก่อน

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

    • @cosdensolutions
      @cosdensolutions  11 หลายเดือนก่อน

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