Gathering detailed insights and metrics for @devesharp/react-hooks-v2
Gathering detailed insights and metrics for @devesharp/react-hooks-v2
Gathering detailed insights and metrics for @devesharp/react-hooks-v2
Gathering detailed insights and metrics for @devesharp/react-hooks-v2
npm install @devesharp/react-hooks-v2
Typescript
Module System
Node Version
NPM Version
TypeScript (99.34%)
JavaScript (0.48%)
HTML (0.17%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
64 Commits
1 Branches
1 Contributors
Updated on Jun 17, 2025
Latest Version
1.0.38
Package Id
@devesharp/react-hooks-v2@1.0.38
Unpacked Size
290.44 kB
Size
60.97 kB
File Count
9
NPM Version
11.0.0
Node Version
20.18.1
Published on
Jun 20, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
7
22
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
1export default tseslint.config({ 2 extends: [ 3 // Remove ...tseslint.configs.recommended and replace with this 4 ...tseslint.configs.recommendedTypeChecked, 5 // Alternatively, use this for stricter rules 6 ...tseslint.configs.strictTypeChecked, 7 // Optionally, add this for stylistic rules 8 ...tseslint.configs.stylisticTypeChecked, 9 ], 10 languageOptions: { 11 // other options... 12 parserOptions: { 13 project: ['./tsconfig.node.json', './tsconfig.app.json'], 14 tsconfigRootDir: import.meta.dirname, 15 }, 16 }, 17})
You can also install eslint-plugin-react-x and eslint-plugin-react-dom for React-specific lint rules:
1// eslint.config.js 2import reactX from 'eslint-plugin-react-x' 3import reactDom from 'eslint-plugin-react-dom' 4 5export default tseslint.config({ 6 plugins: { 7 // Add the react-x and react-dom plugins 8 'react-x': reactX, 9 'react-dom': reactDom, 10 }, 11 rules: { 12 // other rules... 13 // Enable its recommended typescript rules 14 ...reactX.configs['recommended-typescript'].rules, 15 ...reactDom.configs.recommended.rules, 16 }, 17})
Uma biblioteca de hooks customizados para React, desenvolvida em TypeScript.
1npm install my-hooks-lib 2# ou 3yarn add my-hooks-lib 4# ou 5pnpm add my-hooks-lib
1import { useDebounce, useLocalStorage, useToggle } from 'my-hooks-lib'
Hook para debounce de valores, útil para otimizar pesquisas e inputs.
1import { useDebounce } from 'my-hooks-lib' 2 3function SearchComponent() { 4 const [searchTerm, setSearchTerm] = useState('') 5 const debouncedSearchTerm = useDebounce(searchTerm, 500) 6 7 useEffect(() => { 8 if (debouncedSearchTerm) { 9 // Fazer busca apenas após 500ms de inatividade 10 performSearch(debouncedSearchTerm) 11 } 12 }, [debouncedSearchTerm]) 13 14 return ( 15 <input 16 value={searchTerm} 17 onChange={(e) => setSearchTerm(e.target.value)} 18 placeholder="Digite para buscar..." 19 /> 20 ) 21}
Hook para verificar se o componente ainda está montado, útil para evitar vazamentos de memória.
1import { useIsMounted } from 'my-hooks-lib' 2 3function AsyncComponent() { 4 const isMounted = useIsMounted() 5 const [data, setData] = useState(null) 6 7 useEffect(() => { 8 fetchData().then(result => { 9 if (isMounted()) { 10 setData(result) 11 } 12 }) 13 }, [isMounted]) 14 15 return <div>{data}</div> 16}
Hook para gerenciar dados no localStorage com sincronização entre abas.
1import { useLocalStorage } from 'my-hooks-lib' 2 3function SettingsComponent() { 4 const [theme, setTheme] = useLocalStorage('theme', 'light') 5 const [user, setUser] = useLocalStorage('user', { name: '', email: '' }) 6 7 return ( 8 <div> 9 <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}> 10 Tema atual: {theme} 11 </button> 12 <input 13 value={user.name} 14 onChange={(e) => setUser(prev => ({ ...prev, name: e.target.value }))} 15 placeholder="Nome" 16 /> 17 </div> 18 ) 19}
Hook para gerenciar estados booleanos com funções de toggle.
1import { useToggle } from 'my-hooks-lib' 2 3function ModalComponent() { 4 const [isOpen, toggle, setIsOpen] = useToggle(false) 5 6 return ( 7 <div> 8 <button onClick={toggle}> 9 {isOpen ? 'Fechar' : 'Abrir'} Modal 10 </button> 11 <button onClick={() => setIsOpen(true)}> 12 Forçar Abrir 13 </button> 14 {isOpen && <div>Conteúdo do Modal</div>} 15 </div> 16 ) 17}
Hook para fazer requisições HTTP com estados de loading e error.
1import { useFetch } from 'my-hooks-lib' 2 3function UserProfile({ userId }: { userId: string }) { 4 const { data, loading, error } = useFetch(`/api/users/${userId}`) 5 6 if (loading) return <div>Carregando...</div> 7 if (error) return <div>Erro: {error}</div> 8 if (!data) return <div>Usuário não encontrado</div> 9 10 return ( 11 <div> 12 <h1>{data.name}</h1> 13 <p>{data.email}</p> 14 </div> 15 ) 16}
1import { useViewList } from '@devesharp/react-hooks-v2'; 2 3function UserList() { 4 const { 5 resources: users, 6 resourcesTotal, 7 isSearching, 8 isFirstPage, 9 isLastPage, 10 setFilters, 11 nextPage, 12 previousPage, 13 setSort, 14 } = useViewList<User, UserFilters>({ 15 resolveResources: async (filters) => { 16 const response = await fetch('/api/users', { 17 method: 'POST', 18 body: JSON.stringify(filters), 19 }); 20 return response.json(); 21 }, 22 limit: 10, 23 // Novos callbacks para eventos 24 onBeforeSearch: (filters) => { 25 console.log('Iniciando busca:', filters); 26 }, 27 onAfterSearch: (result) => { 28 if (result.success) { 29 console.log(`Carregados ${result.data?.results.length} usuários`); 30 } else { 31 console.error('Erro na busca:', result.error); 32 } 33 }, 34 onChangeFilters: (newFilters, previousFilters) => { 35 // Sincronizar com URL 36 const params = new URLSearchParams(); 37 if (newFilters.search) params.set('search', newFilters.search); 38 window.history.replaceState({}, '', `?${params.toString()}`); 39 }, 40 }); 41 42 return ( 43 <div> 44 {/* Busca */} 45 <input 46 type="text" 47 placeholder="Buscar usuários..." 48 onChange={(e) => setFilters({ search: e.target.value })} 49 /> 50 51 {/* Ordenação */} 52 <select onChange={(e) => { 53 const [column, direction] = e.target.value.split(':'); 54 setSort(column ? { column, direction: direction as 'asc' | 'desc' } : null); 55 }}> 56 <option value="">Sem ordenação</option> 57 <option value="name:asc">Nome (A-Z)</option> 58 <option value="name:desc">Nome (Z-A)</option> 59 </select> 60 61 {/* Lista */} 62 {isSearching && <div>Carregando...</div>} 63 {users.map(user => ( 64 <div key={user.id}> 65 <h3>{user.name}</h3> 66 <p>{user.email}</p> 67 </div> 68 ))} 69 70 {/* Paginação */} 71 <button onClick={previousPage} disabled={isFirstPage}> 72 Anterior 73 </button> 74 <span>Total: {resourcesTotal}</span> 75 <button onClick={nextPage} disabled={isLastPage}> 76 Próxima 77 </button> 78 </div> 79 ); 80}
Navegação:
nextPage()
: Avança para a próxima páginapreviousPage()
: Volta para a página anteriorsetPage(pageNumber)
: Navega para uma página específica (começando em 0)retry()
: Tenta novamente a última requisição que falhouFiltros:
setFilters(newFilters)
: Atualiza filtros e reinicia a buscafilters
: Estado atual dos filtros (inclui offset para paginação)Ordenação:
setSort(sort)
: Atualiza ordenação mantendo a página atualinitialSort
: Define ordenação inicial (padrão: null
)null
ou { column: string | null, direction: 'asc' | 'desc' }
Manipulação de Recursos:
pushResource(resource)
: Adiciona um novo recurso à listaupdateResource(id, resource)
: Substitui completamente um recursoputResource(id, partialResource)
: Atualiza parcialmente um recursodeleteResource(id)
: Remove um recurso da listadeleteManyResources(ids)
: Remove múltiplos recursoschangePosition(id, newPosition)
: Altera a posição de um recursoEstados:
isSearching
: Indica se uma busca está em andamentoisErrorOnSearching
: Indica se houve erro na buscaisFirstPage
: Indica se está na primeira páginaisLastPage
: Indica se está na última página1# Build da biblioteca 2npm run build 3 4# Linting 5npm run lint 6 7# Desenvolvimento (se usando com Vite) 8npm run dev
my-hooks-lib/
├── src/
│ ├── hooks/
│ │ ├── useDebounce.ts
│ │ ├── useIsMounted.ts
│ │ ├── useLocalStorage.ts
│ │ ├── useToggle.ts
│ │ ├── useFetch.ts
│ │ └── index.ts
│ └── index.ts
├── dist/ # Arquivos compilados
├── package.json
├── tsconfig.json
├── tsup.config.ts
└── README.md
git checkout -b feature/AmazingFeature
)git commit -m 'Add some AmazingFeature'
)git push origin feature/AmazingFeature
)Este projeto está sob a licença MIT. Veja o arquivo LICENSE para mais detalhes.
Este arquivo contém testes abrangentes para o hook useDebounce
.
1# Executar todos os testes 2npm run test 3 4# Executar testes uma vez 5npm run test:run 6 7# Executar testes com coverage 8npm run test:coverage
Os testes cobrem:
No vulnerabilities found.
No security vulnerabilities found.