React & Modern Javascript
306 subscribers
43 photos
17 videos
15 files
245 links
React for Developers 🚀🚀
Useful Articles📃
DailyTips⚡️
Introduction videos💫
Courses🗃
Covering the Updates of Modern Web Development!🌎

Link : t.me/ReactDev
Contact Us if You Have Any Questions or Suggestions:
@MrGh0st
@stfuBlyat
Download Telegram
There are hundreds of custom React hooks to access the local storage out there. But I was tempted to create my own using useSyncExternalStore since I figured it's the proper hooks for this kind of use case. Now I'm sure there are already a package that does exactly what I want, but I wanted to create it by myself, for the sake of learning.

This was my first attempt.

const useLocalStorage = (
key: string,
initialValue: string
) => {
const data = useSyncExternalStore(
(onChange) => {
window.addEventListener("storage", onChange);
return () => {
window.removeEventListener("storage", onChange);
};
},
() => {
const data = localStorage.getItem(key);
return data || initialValue;
},
() => initialValue
);

const setData = useCallback(
(value: string) => {
localStorage.setItem(key, value);
},
[key]
);

return [data, setData] as const;
};



Everything seemed to work at first. When I called setData function, the value was persisted in the local storage. But then I noticed that the data value was not updated which didn't re-render the component that used the hook in result. The weird thing was that when I directly modified the value in the local storage, the data value was updated and the component re-rendered. That caused me to think that the change subscription of useSyncExternalStore wasn indeed working.

After few hours of debugging, I finally reached out to my sometimes-genius-sometimes-idiot companion, the gpt-4o which I am using via Supermaven. It immediately pointed out the problem with the code. At first, I didn't believe its explanation so I asked for the proof by giving me the documentation link. By the way, you should not blindly trust what LLM says. Always verify! Anyway, it gave me the link and once again I learned something new thanks to AI.

So the problem is that the "storage" events are only fired when local storage is changed by a different document, not the document where the change originated. It's properly documented in the MDN docs but I didn't know it. So when I save the value in the local storage from the setData function, the event is not fired hence the useSyncExternalStore doesn't return the updated value.

Equipped with this knowledge, I was able to fix the code by adding a custom event listener:

const useLocalStorage = (key: string, initialValue?: string | null) => {
const data = useSyncExternalStore(
(onChange) => {
const onStorageEvent = (e: Event) => {
const customEvent = e as CustomEvent;
if (customEvent.detail.key === key) {
onChange();
}
};
window.addEventListener("storage", onChange);
window.addEventListener(
"local-storage-change",
onStorageEvent as EventListener
);
return () => {
window.removeEventListener("storage", onChange);
window.removeEventListener(
"local-storage-change",
onStorageEvent as EventListener
);
};
},
() => {
const data = localStorage.getItem(key);
return data || initialValue;
},
() => initialValue
);

const setData = useCallback(
(value: string) => {
localStorage.setItem(key, value);
window.dispatchEvent(
new CustomEvent("local-storage-change", { detail: { key } })
);
},
[key]
);

return [data, setData] as const;
};


This custom hook basically does two things:

1. listens to the storage event and the custom event local-storage-change.
2. sends a custom event local-storage-change after storing the value in the local storage.

I still add the official storage event listener because I want the component to still re-redner when the local storage is changed by another document.

Source: https://bit.ly/4eF3QbX

#react #hooks
@ReactDev 🚀
Forwarded from Mohammad
💻 استخدام برنامه نویس :
Sr. Full-stack (TypeScript) Developer

🕰 نوع همکاری :
Remote 🌎

📍⁣⁣ استان(شهر) :
Remote 🌎

🏢 نام شرکت یا استارت آپ :
IFSGuide.com

💭 درباره ی مجموعه :
IFS Guide is an international startup based in North America and Europe, dedicated to making mental health accessible to all through AI-powered technology. With a small but agile team, we have developed a successful app that provides users with therapy and self-improvement tools via AI, using the fastest-growing therapy model, Internal Family Systems (IFS). IFS Guide was founded by a serial entrepreneur with a successful exit and is backed by a team with a proven track record of success.



⚖️ شرایط پذیرش :
Expertise in TypeScript with Experience in Next.js and Firebase/GCP
AI Enthusiast with a Focus on Coding Tools
Strong Product-Centric Approach to Development
Solution-Oriented Thinking with a Product-First Perspective
Commitment to Taking Ownership and Driving Outcomes
Deep Passion for Building and Scaling Startups


💵 مزایا و میزان حقوق :
- Great competitive pay & benefits package
Flexible work hours
Flexible location.
Full Health Insurance or equivalent in salary compensation
Create a brand new code base and put your own best practices in places.


📲 اطلاعات تماس :
m@ifsguide.com

____


با انتشار این آگهی در سرکار گذاشتن دیگران سهیم باشید 🗣

👇👇

🆔 Channel : @TehranReact_jobs
👨‍💼Support : @Mgoldast
Happy New Year, React Developers! 🎉

Here’s to another year of building amazing UIs, sharing knowledge, and pushing the web forward! Let’s make 2025 a year of growth, creativity, and innovation. Keep Reacting and stay awesome! 🚀😎⚛️