REACT_LIB Telegram 718
Custom Hooks

Часто мы пишем один и тот же код в разных компонентах: работа с localStorage, отслеживание размеров окна, дебаунс запросов. И вот тут кастомные хуки реально спасают.

Например, простой хук для работы с localStorage 👇


import { useState } from "react";

function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});

const setStoredValue = (newValue: T) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
};

return [value, setStoredValue] as const;
}

export default useLocalStorage;


Теперь можно использовать так:


const [theme, setTheme] = useLocalStorage("theme", "light");


🔥 Плюсы:

- код становится чище и переиспользуемым;
- избавляемся от дублирования логики;
- легко тестировать и поддерживать.

Я заметил, что когда начинаешь собирать библиотеку своих хуков, разработка ускоряется в разы. Советую прямо сегодня завести папку hooks и складывать туда такие полезности.

✍️ @React_lib
👍4



tgoop.com/React_lib/718
Create:
Last Update:

Custom Hooks

Часто мы пишем один и тот же код в разных компонентах: работа с localStorage, отслеживание размеров окна, дебаунс запросов. И вот тут кастомные хуки реально спасают.

Например, простой хук для работы с localStorage 👇


import { useState } from "react";

function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});

const setStoredValue = (newValue: T) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
};

return [value, setStoredValue] as const;
}

export default useLocalStorage;


Теперь можно использовать так:


const [theme, setTheme] = useLocalStorage("theme", "light");


🔥 Плюсы:

- код становится чище и переиспользуемым;
- избавляемся от дублирования логики;
- легко тестировать и поддерживать.

Я заметил, что когда начинаешь собирать библиотеку своих хуков, разработка ускоряется в разы. Советую прямо сегодня завести папку hooks и складывать туда такие полезности.

✍️ @React_lib

BY React




Share with your friend now:
tgoop.com/React_lib/718

View MORE
Open in Telegram


Telegram News

Date: |

But a Telegram statement also said: "Any requests related to political censorship or limiting human rights such as the rights to free speech or assembly are not and will not be considered." Joined by Telegram's representative in Brazil, Alan Campos, Perekopsky noted the platform was unable to cater to some of the TSE requests due to the company's operational setup. But Perekopsky added that these requests could be studied for future implementation. While some crypto traders move toward screaming as a coping mechanism, many mental health experts have argued that “scream therapy” is pseudoscience. Scientific research or no, it obviously feels good. End-to-end encryption is an important feature in messaging, as it's the first step in protecting users from surveillance. Over 33,000 people sent out over 1,000 doxxing messages in the group. Although the administrators tried to delete all of the messages, the posting speed was far too much for them to keep up.
from us


Telegram React
FROM American