All authors

Claude Skills by HoangNguyen0403
github.com/HoangNguyen04031,434 skills30 installs1,975 views
- React Native PerformanceUse a caching image implementation such as react-native-fast-image where its tradeoffs fit the app, and serve appropriately sized WebP assets instead of large PNGs. Give images known dimensions to reduce layout work and avoid decoding oversized originals. For image-heavy lists, combine image caching with a tuned FlatList, memoized rows, stable keys, and incremental loading. Measure memory, cache hit behavior, startup, and scroll frame rate on representative devices; caching alone will not fix...Votes: 0GitHub stars: 549
- React Native Platform SpecificFor a small difference in a shared component, use Platform.select or a guarded Platform.OS branch: const paddingTop = Platform.select({ ios: 24, android: 12, default: 12 }); Keep the shared style in StyleSheet.create and use the platform value only for the actual difference. Prefer feature detection over hardcoded OS-version checks, and verify the result on both platforms.Votes: 0GitHub stars: 549
- React Native Platform SpecificCreate a shared Button interface and split the implementation into Button.ios.tsx and Button.android.tsx. React Native resolves the platform-specific file automatically, with Button.tsx as a fallback when appropriate. Keep shared types, contracts, and data behavior in a platform-neutral module; put only the genuinely divergent UI or native behavior in the platform files. If the implementations are mostly alike, keep one component and use Platform.select instead. Test both implementations and ...Votes: 0GitHub stars: 549
- React Native Platform SpecificWrap the iOS-only module behind a small platform-specific adapter, for example a NativeFeature.ios.ts module, and expose a shared TypeScript interface. Import that adapter from platform-neutral code so callers do not spread Platform.OS checks throughout the app. Use an Expo module when one provides the capability; in a bare app use the community or custom native module. Provide an Android fallback or explicit unsupported result, guard calls with feature detection, and test the supported and u...Votes: 0GitHub stars: 549
- React Native SecurityStore authentication tokens in the platform secure keychain/keystore, for example through react-native-keychain, not AsyncStorage. Use biometric protection when the product requires it, keep access behind a small auth-storage abstraction, and use short-lived access tokens with a refresh strategy where possible. Never hardcode secrets or log tokens. Treat the client as untrusted and enforce authorization on the backend; AsyncStorage is suitable only for non-sensitive preferences.Votes: 0GitHub stars: 549
- React Native SecurityFor a high-security financial client, use a maintained certificate-pinning solution such as react-native-ssl-pinning and configure the expected certificate or public-key pins for the API. Enforce HTTPS and keep platform network-security configuration aligned with the client library. Test that a request fails with an untrusted or changed certificate, and monitor pin expiry and rotation. Pinning can brick an old app when certificates rotate, so ship overlapping pins or a planned app update and ...Votes: 0GitHub stars: 549
- React Native SecurityYes. Tokens in deep-link URLs can leak through OS logs, analytics, browser history, notification previews, referrers, screenshots, and copied links. Remove the token from the URL and use a short-lived one-time code that the app exchanges over HTTPS, then store the resulting credential in the platform keychain/keystore. Also whitelist the expected scheme and host, validate and sanitize route parameters, and never log the raw URL. Deep links should be treated as untrusted input, with the backen...Votes: 0GitHub stars: 549
- React Native State ManagementFor a medium-sized app, start with Zustand when the shared state is moderate and you want a small API with selective subscriptions. Use Redux Toolkit when the domain is complex, many teams need strict conventions and middleware, or time-travel/debug tooling and event history are important. Do not put every value in global state: keep form and UI toggles local, use Context for cross-cutting values such as theme or auth, and use a server-state library for API data. Choose based on debugging, te...Votes: 0GitHub stars: 549
- React Native State ManagementTreat API data as server state and use @tanstack/react-query. The query cache owns fetching, deduplication, stale times, refetching, loading, and error states, so the component reads query data directly instead of copying it into useState. Use mutations to update server data and invalidate or update affected query keys. Keep only genuinely local UI state in useState and reserve Zustand or Redux for client state that is not a cache of the server response.Votes: 0GitHub stars: 549
- React Native State ManagementCreate providers for the cross-cutting state and mount them above the navigator, for example ThemeProvider and AuthProvider. Expose typed hooks such as useTheme and useAuth; each hook should throw a useful error if used outside its provider. Consumers then read or update state without passing it through every screen. Keep small UI state local, use Context for theme and auth, and use Zustand or Redux Toolkit if the shared client state becomes complex. For API data, use a query cache rather tha...Votes: 0GitHub stars: 549
- React Native StylingDefine component styles with StyleSheet.create and pass style references or a typed style prop. It keeps styles centralized, validates supported React Native style properties, and avoids creating a new object during every render. Inline objects also make reuse, theming, and review harder; use them only for a genuinely dynamic value that cannot be expressed otherwise. Centralize colors, spacing, and typography in theme tokens, use Flexbox for layout, and keep platform-specific differences in P...Votes: 0GitHub stars: 549
- React Native StylingUse Flexbox as the default layout, with flex and percentage-based dimensions instead of fixed widths. Read the current size with useWindowDimensions when a breakpoint or calculation is necessary, and recompute when the window changes; Dimensions can be used when a one-time measurement is sufficient. Centralize spacing and typography in theme constants, use Platform.select for platform differences, and avoid absolute positioning unless it is essential. Test narrow, wide, rotated, and accessibi...Votes: 0GitHub stars: 549
- React Native StylingUse platform-specific font configuration rather than branching through every component. For a small difference, use Platform.select in a shared StyleSheet; when the style or asset diverges substantially, use .ios and .android files or style modules. Bundle and link the font files correctly for both platforms, register the exact family names, and provide a fallback. Keep font sizes and weights in typography tokens, then test the real font on iOS and Android because family names and available w...Votes: 0GitHub stars: 549
- React Native TestingRender the component with React Native Testing Library, find the control by an accessible role or visible text, press it, and assert the user-visible result: render(<Counter />); fireEvent.press(getByRole('button', { name: /increment/i })); expect(getByText('Count: 1')).toBeTruthy(); Prefer getByRole or getByText over testID, and use waitFor or findBy queries for asynchronous updates. Test behavior rather than component implementation details.Votes: 0GitHub stars: 549
- React Native TestingMock the native module at the Jest boundary, for example with jest.mock for @react-native-async-storage/async-storage, and provide deterministic getItem, setItem, and removeItem implementations. Reset or clear mock state between tests so one test's stored value cannot affect another. Render the component through any required providers, exercise it with RNTL user-facing queries and events, and assert the resulting behavior. Keep the mock narrow and avoid testing the module's internals; integra...Votes: 0GitHub stars: 549
- React Native TestingNo. Accessing component.state or component.props tests implementation details and is not the React Native Testing Library model. Render the component, interact as a user would, and assert visible text, roles, accessibility state, callbacks, or other observable outcomes. Use getByRole and getByText when possible, waitFor or findBy queries for async behavior, and use testID only when no accessible query is appropriate. Keep snapshots limited because they are brittle; focus coverage on critical ...Votes: 0GitHub stars: 549
- React Component PatternsUse the Compound Components pattern: `<Select>` owns the value and `React.createContext()` shares state, while `<Select.Option>` consumes that Context directly. ```tsx <Select value={value} onChange={setValue}> <Select.Option value="a">A</Select.Option> </Select> ```Votes: 0GitHub stars: 549
- React Component PatternsThis is Prop Drilling. Create a Context provider at the common ancestor and let the deep component read the value with `useContext()`. For complex global state, use Zustand; Compound Components or Render Props can also remove the unnecessary hierarchy.Votes: 0GitHub stars: 549
- React Component PatternsUse a ternary instead of `&&`: `{count > 0 ? <List /> : null}`. JavaScript evaluates `0 && <List />` to `0`, and React renders that literal 0 into the DOM. An explicit boolean check avoids the bug.Votes: 0GitHub stars: 549
- React HooksObjects are recreated on each render, so strict identity changes and the effect loops. Use primitive dependencies when possible or memoize the config: ```tsx const config = useMemo(() => ({ id, type }), [id, type]); ```Votes: 0GitHub stars: 549
- React HooksPrefer SWR or TanStack Query for server data. If `useEffect` owns the request, create an `AbortController`, pass its signal, and return cleanup that aborts it. Keep the dependency array accurate and do not use an effect to derive render state.Votes: 0GitHub stars: 549
- React HooksImplement a custom `useOnlineStatus` hook with `useState` and `useEffect`. Register online/offline listeners at the top level, update state from the handler, and return cleanup that removes both listeners. Keep the effect dependency array stable.Votes: 0GitHub stars: 549
- React PerformanceSequential awaits create a request waterfall. Parallelize independent work with `Promise.all`, for example `Promise.all([getUser(id), getOrders(id)])`, then fetch only the data that depends on those results. Use Suspense boundaries to stream slow branches and profile the result.Votes: 0GitHub stars: 549
- React PerformanceReduce bundle cost by removing barrel files, using `React.lazy` or dynamic imports for heavy components, and replacing oversized dependencies where appropriate. Analyze with a bundle tool and keep named imports so tree-shaking works; verify the initial load after the change.Votes: 0GitHub stars: 549
- React PerformanceSplit Context into separate State and Dispatch objects so dispatch-only consumers do not re-render with state changes. For high-frequency updates across many components, use Zustand or Jotai, then profile render counts to confirm the re-render reduction.Votes: 0GitHub stars: 549
- React SecurityMove the JWT out of `localStorage`; any XSS can read it. Store it in an `HttpOnly; Secure` cookie set by the backend: ```http Set-Cookie: access_token=<jwt>; HttpOnly; Secure; SameSite=Strict; Path=/ ``` Call the API with cookies enabled: ```ts fetch("/api/profile", { credentials: "include", }); ``` For state-changing `PUT`/`POST`/`DELETE` requests, add CSRF-token protection. Use `SameSite=Strict` where applicable; cross-site deployments require `SameSite=None; Secure` plus robust CSRF protec...Votes: 0GitHub stars: 549
- React SecurityThis is an IDOR/BOLA authorization vulnerability: the backend trusts the `userId` from the URL. Assumption: the URL is something like `/users/:userId`. Fix authorization server-side on every affected endpoint: ```ts // GET /api/users/:userId const requestedId = req.params.userId; const authenticatedUser = req.user; if (authenticatedUser.id !== requestedId && !authenticatedUser.roles.includes("admin")) { return res.status(404).json({ error: "Not found" }); // or 403 } return res.json(await use...Votes: 0GitHub stars: 549
- React SecurityAssuming you use npm: 1. Check current issues: ```bash npm audit npm outdated ``` 2. Review available updates with `npm-check-updates`: ```bash npx npm-check-updates npx npm-check-updates -u npm install ``` 3. Update carefully—handle major-version changes individually, review changelogs, and run your tests/build: ```bash npm test npm run build ``` 4. Run the audit again and address remaining vulnerabilities: ```bash npm audit npm audit fix ``` 5. Pin specific dependency versions in `package.j...Votes: 0GitHub stars: 549
- React State ManagementUse Context for low-frequency global auth state, such as an `AuthContext` with the user and logout action. Use Zustand for frequent or broader global updates, and pair auth/session fetching with React Query or SWR so the cache remains the source of truth.Votes: 0GitHub stars: 549
- React State ManagementThis is the server-cache-as-UI-state anti-pattern. Use React Query or SWR as the cache source of truth; use its mutation and invalidation APIs instead of syncing the response through `useEffect` and `useState`.Votes: 0GitHub stars: 549
- React State ManagementKeep Redux Toolkit when the large app needs complex middleware or time-travel debugging; RTK's `createSlice`, `createAsyncThunk`, and RTK Query reduce boilerplate. Consider Zustand for smaller or medium scopes, and migrate slice by slice rather than all at once.Votes: 0GitHub stars: 549
- React TestingUse RTL with the AAA pattern: ```tsx render(<UserCard user={{ name: 'Alice', email: 'alice@test.com' }} />); expect(screen.getByRole('heading', { name: 'Alice' })).toBeInTheDocument(); ``` Prefer `getByRole` for accessible behavior and avoid checking internal state.Votes: 0GitHub stars: 549
- React TestingThis violates the no-real-network rule. Use MSW (Mock Service Worker) to intercept API calls, start the server in test setup, reset handlers after each test, and close it after the suite. Tests should assert user-visible behavior, not network availability.Votes: 0GitHub stars: 549
- React TestingUse `userEvent` asynchronously: ```tsx const user = userEvent.setup(); await user.type(screen.getByLabelText(/email/i), 'test@test.com'); await user.click(screen.getByRole('button', { name: /submit/i })); expect(await screen.findByText(/success/i)).toBeInTheDocument(); ``` Prefer `findByText` for results that appear after submission and avoid `fireEvent` for normal user interactions.Votes: 0GitHub stars: 549
- React ToolingProfile first with the React DevTools Flamegraph, then enable Highlight Updates or `why-did-you-render` in development to identify the prop/state change. Fix the measured hotspot and re-check render counts; do not add memoization by reflex.Votes: 0GitHub stars: 549
- React ToolingUse Vite rather than CRA for a new standalone React project; CRA is deprecated. Vite provides fast builds and HMR, supports `.env`, and works with `@vitejs/plugin-react`. Use Next.js tooling for a Next.js app.Votes: 0GitHub stars: 549
- React ToolingUse `source-map-explorer` for webpack or `rollup-plugin-visualizer` for Vite to analyze the bundle. Inspect large vendor chunks, duplicated dependencies, and whole-library imports; verify the production bundle after removing the bloat.Votes: 0GitHub stars: 549
- React TypescriptUse an explicit interface and `PropsWithChildren` or `ReactNode`: ```tsx interface Props { className?: string; children: React.ReactNode; } function Panel({ className, children }: Props): JSX.Element { return <div className={className}>{children}</div>; } ``` Avoid `React.FC`; use `ComponentPropsWithoutRef<'div'>` when extending native div props.Votes: 0GitHub stars: 549
- React TypescriptUse a generic component: ```tsx interface ListProps<T> { items: T[]; renderItem: (item: T) => ReactNode; keyExtractor: (item: T) => string; } function List<T,>(props: ListProps<T>): JSX.Element { /* render props.items */ return <>{props.items.map(props.renderItem)}</>; } ``` The generic `<T,>` comma avoids TSX parser ambiguity and preserves the item type.Votes: 0GitHub stars: 549
- React TypescriptYes. Avoid `React.FC`: its implicit children and extra typing behavior are less explicit. Define an `interface Props` and a plain function instead: ```tsx interface Props { title: string; children?: React.ReactNode; } function Component({ title, children }: Props): JSX.Element { return <section>{title}{children}</section>; } ```Votes: 0GitHub stars: 549
- Spring Boot Api DesignFor Spring Boot 3, use Springdoc's WebMVC starter rather than manually hosting Swagger UI: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>...</version> </dependency> ``` Document the controller contract explicitly: ```java @Operation(summary = "Find an order") @ApiResponse(responseCode = "200", description = "Order found") @GetMapping("/{id}") OrderResponse get(@PathVariable UUID id) { ... } ``` Use typed DTOs, prefer...Votes: 0GitHub stars: 549
- Spring Boot Api DesignPrefer URI versioning for a Spring Boot REST API, for example `/api/v1/orders`. It is visible in links, straightforward to cache and route, and easy to test. Keep the version at the resource boundary rather than duplicating version decisions throughout the service layer: ```java @RestController @RequestMapping("/api/v1/orders") final class OrderController { ... } ``` When the contract changes incompatibly, add `/api/v2` with its own DTOs and controller adapter. Services and domain logic can r...Votes: 0GitHub stars: 549
- Spring Boot Api DesignReturn a typed DTO, preferably a Java record, instead of `Map<String, Object>`: ```java public record UserResponse(UUID id, String name, String email) {} @GetMapping("/{id}") UserResponse get(@PathVariable UUID id) { User user = service.find(id); return new UserResponse(user.id(), user.name(), user.email()); } ``` Use separate request and response DTOs when their contracts differ, and put examples and schema metadata on those DTOs with `@Schema`. The controller should handle HTTP concerns, va...Votes: 0GitHub stars: 549
- Spring Boot ArchitectureOrganize by business feature, with layers inside each feature, rather than one global `controllers`, `services`, and `repositories` package: ```text com.example.app order/ OrderController.java // web adapter OrderService.java // business orchestration OrderRepository.java // persistence adapter/port OrderRequest.java OrderResponse.java // records user/ ... shared/ error/ ``` The dependency direction is inward: web depends on service/domain, and persistence impl...Votes: 0GitHub stars: 549
- Spring Boot ArchitectureCircular dependencies usually mean two components own responsibilities that are too tightly coupled. First map the dependency graph and move shared business rules into a third service or domain component. Keep the intended direction explicit: controllers/adapters depend on services, and services do not depend on controllers. For a collaboration that is naturally asynchronous, replace the direct call with an event. For example, `OrderService` can publish `OrderPlaced`; notification handling co...Votes: 0GitHub stars: 549
- Spring Boot ArchitectureNo. A controller should be a thin web adapter: bind the request, apply `@Valid`, map DTOs, delegate to a service, and select the HTTP response. Business rules, orchestration, and transaction boundaries belong in the service layer. ```java @RestController @RequiredArgsConstructor final class OrderController { private final OrderService service; @PostMapping("/orders") OrderResponse create(@Valid @RequestBody CreateOrderRequest request) { return service.create(request); } } ``` Use immutable re...Votes: 0GitHub stars: 549
- Spring Boot Best PracticesUse a small set of enforceable production defaults: - Prefer constructor injection, with final dependencies; Lombok `@RequiredArgsConstructor` is fine. Avoid field `@Autowired` injection. - Bind configuration with validated `@ConfigurationProperties` records, use `application.yaml` and profile files such as `application-dev.yml`/`application-prod.yml`, and select profiles with `SPRING_PROFILES_ACTIVE`. Never hardcode secrets. - Use immutable record DTOs and validate inputs with Jakarta Bean V...Votes: 0GitHub stars: 549
- Spring Boot Best PracticesAvoid field injection with `@Autowired`. It hides a class's dependencies, makes the object harder to instantiate in a unit test, allows dependencies to be reassigned, and can conceal an overly coupled design. Prefer constructor injection with final fields: ```java @Service @RequiredArgsConstructor public class OrderService { private final OrderRepository orders; private final PaymentClient payments; } ``` Spring will use the single constructor automatically; without Lombok, write that constru...Votes: 0GitHub stars: 549
- Spring Boot Best PracticesUse typed, profile-aware configuration rather than scattering `@Value` strings: ```java @ConfigurationProperties("payments") @Validated public record PaymentProperties(@NotEmpty String baseUrl, @NotNull Duration timeout) {} ``` Register it with `@ConfigurationPropertiesScan` (or `@EnableConfigurationProperties`) and keep structured defaults in `application.yaml`. Put environment-specific overrides in `application-dev.yml` and `application-prod.yml`, selecting one with `SPRING_PROFILES_ACTIVE`...Votes: 0GitHub stars: 549
- Spring Boot Data AccessUse Spring Data JPA when the application is primarily aggregate-oriented CRUD and benefits from entity mapping, repositories, and a unit-of-work model. It is the default fit for the conventions in this skill: prefer `JpaRepository` and derived query methods, use JPQL or `@EntityGraph` for complex access, and return record projections when a full entity is unnecessary. Choose jOOQ when the workload is SQL-heavy and needs precise vendor-specific SQL, complex reporting, or compile-time SQL shape...Votes: 0GitHub stars: 549