React Custom Hooks: useLocalStorage - Simply Explained!

  Рет қаралды 22,636

Cosden Solutions

Cosden Solutions

9 ай бұрын

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!

Пікірлер: 63
@malekabdelkader9250
@malekabdelkader9250 9 ай бұрын
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 ай бұрын
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.
@mohamed-zhioua
@mohamed-zhioua 9 ай бұрын
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
@eddnufc93
@eddnufc93 8 ай бұрын
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 ай бұрын
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!
@OleksandrKaminiev
@OleksandrKaminiev 8 ай бұрын
Nice explanation. Thank you!
@BradySie-wo6vf
@BradySie-wo6vf 9 ай бұрын
It doesn’t need to be a hook just a regular function will do
@cosdensolutions
@cosdensolutions 9 ай бұрын
better a hook, to re-use it easily and also allow it to have state or other hooks inside
@ivankraev4264
@ivankraev4264 9 ай бұрын
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 ?
@user-ob9qm4br2j
@user-ob9qm4br2j 3 ай бұрын
Brother your teaching technique daymmm🤯
@andrea_zero
@andrea_zero 9 ай бұрын
Very useful!! Thanks
@learnearn8721
@learnearn8721 8 ай бұрын
Your tutorial are really helpful thanks a lot 🙏🙏🙏🙏🙏🙏🙏
@ALi-Sloom
@ALi-Sloom 7 ай бұрын
Mann , You're Amazing
@imammaulana6707
@imammaulana6707 2 ай бұрын
You save my day bro 🤩
@abrahamorherhe2434
@abrahamorherhe2434 8 ай бұрын
Thanks for your videos.
@naukaKontoTechniczne
@naukaKontoTechniczne 11 сағат бұрын
Great job!!! Thanks
@Mroskas
@Mroskas 9 ай бұрын
I think a simple and good addition would be to convert get function to generic. Because now we might as well use jsx. 😁
@ravisankarp61
@ravisankarp61 9 ай бұрын
I love this video , thank you.
@ravisankarp61
@ravisankarp61 9 ай бұрын
Do u have a course , I would like to check it if it is in my budget :)
@einfacherkerl3279
@einfacherkerl3279 7 ай бұрын
shouldn't this be done inside useEffect in useLocalStorage?
@osmar6150
@osmar6150 7 ай бұрын
You are the best
@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?
@Tommy-ev6gv
@Tommy-ev6gv 9 ай бұрын
It's a css framework called Tailwind.
@cosdensolutions
@cosdensolutions 9 ай бұрын
Tailwind!
@beb316ratnesh2
@beb316ratnesh2 3 ай бұрын
Nice Explanation! The only problem: Did not explained what custom hooks are, their purpose, use cases etc. Not an ideal choice for a beginner.
@bmielki
@bmielki 8 ай бұрын
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 ай бұрын
so you didn't have to always pass the key to every function
@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
@marcossequeira5433
@marcossequeira5433 9 ай бұрын
Just for curious it's any clean way to detect changes in the local storage?
@cosdensolutions
@cosdensolutions 9 ай бұрын
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
@fabriziogiovannetti3020
@fabriziogiovannetti3020 9 ай бұрын
The order of setItems, getItems and removeItems is different in the useLocalStorage declaration than its usage. It doesn’t matter?
@cosdensolutions
@cosdensolutions 9 ай бұрын
nope, because they are named and it's an object!
@fabriziogiovannetti3020
@fabriziogiovannetti3020 9 ай бұрын
Thank you!
@sachinmalik5837
@sachinmalik5837 9 ай бұрын
Haha, I like how you always kinda make way for subscribe message right there in code.
@cosdensolutions
@cosdensolutions 9 ай бұрын
😉
@alvinacosta2312
@alvinacosta2312 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
@@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.
@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 8 ай бұрын
@@cosdensolutions Thanks, keep up the good work
@TurkeyMaster
@TurkeyMaster 9 ай бұрын
"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 ай бұрын
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 !
@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
@balduin_b4334
@balduin_b4334 9 ай бұрын
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 ай бұрын
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
@riadqerimi6701
@riadqerimi6701 7 ай бұрын
Tell us about this copilot in vsco
@cosdensolutions
@cosdensolutions 7 ай бұрын
have video on it! called my vscode setup
@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.
@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 9 ай бұрын
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 ай бұрын
@@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 ай бұрын
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
Learn React Hooks: useRef - Simply Explained!
12:42
Cosden Solutions
Рет қаралды 83 М.
Custom Hooks in React (Design Patterns)
12:56
Cosden Solutions
Рет қаралды 35 М.
MEU IRMÃO FICOU FAMOSO
00:52
Matheus Kriwat
Рет қаралды 44 МЛН
3M❤️ #thankyou #shorts
00:16
ウエスP -Mr Uekusa- Wes-P
Рет қаралды 11 МЛН
Урок 17. JavaScript. Все о LocalStorage
16:39
Владилен Минин
Рет қаралды 149 М.
Кастомные React-Хуки, useToggle, useLocalStorage
22:20
Михаил Непомнящий
Рет қаралды 18 М.
Reviewing your React Code: Episode #3
14:27
Youssef Benlemlih
Рет қаралды 7 М.
Why Signals Are Better Than React Hooks
16:30
Web Dev Simplified
Рет қаралды 459 М.
React Local Storage Hook - How to Synchronize State and Local Storage in React
7:54
You Are Using useEffect Wrong
14:40
Cosden Solutions
Рет қаралды 32 М.
Learn Custom Hooks In 10 Minutes
9:38
Web Dev Simplified
Рет қаралды 245 М.
LocalStorage was a mistake...
5:33
Josh tried coding
Рет қаралды 46 М.
How to Improve Performance in React with Code Splitting
9:55
PedroTech
Рет қаралды 200 М.