Pattern Library

Grit comes with 89 out of the box patterns that can be leveraged immediately.

Migration Patterns

Migration patterns can be used to automatically migrate you to a new framework or library.

Chai to Jest (chai_to_jest)

Convert Chai test assertions to Jest.

Always braces around arrow function body (es6_arrow_function_braces)

Converts arrow function single expression to to block body

Function expressions to arrow functions (es6_arrow_functions)

Converts function expressions to ES6 arrow functions

Prefer ES6-style exports over module.exports (es6_exports)

Converts CommonJS module.exports to ES6-style exports.

Prefer imports over require (es6_imports)

Converts require statements to ES6-style import.

Upgrade Hathora to Dedicated TS SDK (hathora_ts)

Transform io-ts to zod schema (iots_to_zod)

Transform io-ts schemas to zod schema

Jest to Vitest (jest_to_vitest)

Convert Jest tests to Vitest

Migrate Knockout to React (knockout_to_react)

Knockout.js is an older JavaScript framework that is still used by many developers. This migration helps with migrating your Knockout code to React.

Upgrade Langfuse to v2 (langfuse_node_v2)

Upgrade the Langfuse SDK to v2 following this guide.

Migrate default imports to named imports (migrate_default_imports)

Migrate from TanStack Query 3 to React query 4 (migrating_from_react_query_3_to_react_query_4)

This pattern migrates from React Query v3 to React Query v4. It is the equivalent of the codemod.

Move defined styled components outside component module level. (move-defined-styled-components-outside-module-level)

Creating a styled component inside the render method in React leads to performance issues because it dynamically generates a new component in the DOM on each render. This causes React to discard and recalculate that part of the DOM subtree every time, rather than efficiently updating only the changed parts. This can result in performance bottlenecks and unpredictable behaviour.

Upgrade Mux SDK to v8 (mux_v8)

Upgrade OpenAI SDK to v4 (openai_v4)

Upgrade the OpenAI SDK to v4 following this guide.

Adopt OpenRouter (openrouter)

Protractor to Playwright (protractor_to_playwright)

Protractor to Playwright.

Convert React Class Components to Functional Components (react_to_hooks)

This pattern converts React class components to functional components, with hooks.

Remove Apollo Graphql Schema Directives while migrating from v2 to v3 or v4 (remove-apollo-graphql-schema-directives-for-v3-v4)

The 'schemaDirectives' option in Apollo GraphQL, which was effective in ApolloServer version v2, no longer functions in versions >=3 and above. This change can have significant implications, potentially exposing authenticated endpoints, disabling rate limiting, and more, depending on the directives used. To address this, it is recommended to consult the references on creating custom directives specifically for ApolloServer versions v3 and v4.

JavaScript to TypeScript (js_to_ts)

AngularJS to Angular*

Angular to React*

Linters

These patterns can autofix many common JavaScript mistakes, including issues that eslint doesn't fix automatically.

PreferEarlyReturn (prefer_early_return)

Prefer to use early returns to keep functions flat.

Harden DOM usage*

Miscellaneous

Replace default exports with named exports (_convert_default_exports)

Replaces export default $something with export const $name = $something. The chosen name matches the file name.

Replace default imports with a named import (_convert_default_imports)

Replaces default

No Restricted Imports (_no_restricted_imports)

This pattern provides the equivalent of the no-restricted-imports rule in ESLint.

Add try catch for async functions (add_try_catch_async_functions)

Add Type To Caught Errors (add_type_caught_errors)

Add any type annotation to caught errors. It is a common source of tsc errors.

Calling setState on the current state is always a no-op. so change the state like $Y(!$X) instead. (calling-set-state-on-current-state)

Calling setState on the current state is always a no-op. Did you mean to change the state like $Y(!$X) instead?

Convert CodeceptJS to Playwright (codecept_to_playwright)

Migrate from CodeceptJS to Playwright.

Rewrite PureComponent ⇒ Component (convert_PureComponent_to_Component)

If a PureComponent has the shouldComponentUpdate method, convert it to a regular Component.

Convert <></> ⇒ React.Fragment (convert_fragment_to_react_fragment)

React suggest to use React.Fragment besides <>

Rewrite x == -0 ⇒ Object.is(x, -0) (convert_negative_zero_equality_check_to_object_is)

Convert any equality check with -0 to the more precise Object.is.

Non-strict == ⇒ strict === (enforce_strict_equality_check)

Convert non-strict equality checking, using ==, to the strict version, using ===.

Prefer require over imports (es6_imports_to_require)

Converts ES6-style import to require statements.

⇒ explicit conversion between types (explicit_type_conversion)

Use explicit conversions between types, e.g., '' + x => String(s).

⇒ Find uncaught HTTP requests (find-uncaught-http-request)

Find uncaught HTTP requests and wrap it with try {} catch{ }

Insert a .jsx extension on files that contain JSX (fix_jsx_file_extension)

Files containing JSX should have a .jsx extension.

Fix for counter direction (for_direction)

If a for counter moves in the wrong direction the loop will run infinitely. Mostly, an infinite for loop is a typo and causes a bug.

GraphQL Sever v3 csrf prevention (graphql-v3-csrf-prevention)

The Apollo GraphQL server lacks the 'csrfPrevention' option. This option is 'false' by the default in v3 of the Apollo GraphQL v3, which can enable CSRF attacks.

GraphQL Sever v4 csrf prevention (graphql-v4-csrf-prevention)

The Apollo GraphQL server sets the 'csrfPrevention' option to false. This can enable CSRF attacks.

Import management (importing)

Grit includes standard patterns for declaratively adding, removing, and updating imports.

Rewrite indexOf(...) === -1 ⇒ includes (index_of_to_includes)

ES7 introduced the includes method for arrays so bitwise and comparisons to -1 are no longer needed.

Rewrite innerHtml ⇒ innerText (inner_html_to_inner_text)

Replaces innerHtml with innerText, which is safer in most cases.

intelligent_useEffect_to_useLayoutEffect (intelligent_useEffect_to_useLayoutEffect)

If a useEffect depends on layout etc. it should switch to useLayoutEffect.

Consolidate Jest arrayContaining assertions (jest_array_containing)

expect.arrayContaining can be used to validate an array containing multiple different elements, so multiple statements are not required.

No skipped tests (jest_no_skipped_tests)

Disable skipping Jest tests without an explanation.

Remove <a> Tags From Link Components (next13_links)

Migrate Link component children to Next13

Remove alert statement (no_alert)

JavaScript’s alert is often used while debugging code, which should be removed before deployment to production.

Rename anonymous default export functions ⇒ main (no_anonymous_default_export)

Replaces export default function () { } with export default function main () { } and export default () => { } with const main = () => { }; export default main

Rewrite Array(a, b, ...) ⇒ [a, b, ...] (no_array_constructor)

The literal notation avoids the single-argument pitfall or the Array global being redefined.

Remove async from Promise (no_async_promise_executor)

The Promise is already executed asynchronously and exceptions thrown by the function will be lost.

Rewrite & ⇒ &&, | ⇒ || (no_bitwise)

Bitwise operators & or | are often used by mistake instead of && or ||, which can cause unexpected errors.

Remove arguments.caller and arguments.callee (no_caller)

arguments.caller and arguments.called have been deprecated.

Remove confirm statement (no_confirm)

JavaScript’s confirm function is widely considered to be obtrusive as UI elements and should be replaced by a more appropriate custom UI implementation.

Remove console.log (no_console_log)

Remove console.log statements.

Remove unreachable code (no_dead_code)

Remove unreachable code found after return / throw / continue or break statements.

Remove debugger statement (no_debugger)

The code in production should not contain a debugger. It causes the browser to stop executing the code and open the debugger.

Compare null using === or !== (no_eq_null)

Comparing to null needs a type-checking operator (=== or !==), to avoid incorrect results when the value is undefined.

No inline `if` and `else` statements (no_inline_if)

The if and else statements should not be used inline. Instead, use a block statement.

Rewrite __iterator__ property ⇒ _iterator_ (no_iterator)

Use _iterator_ instead of __iterator__. __iterator__ is obsolete and is not implemented by all browsers.

Rewrite new Object() ⇒ {} (no_new_object)

The {} literal form is a more concise way of creating an object.

Rewrite new Symbol ⇒ Symbol (no_new_symbol)

Calling Symbol with the new operator throws a TypeError exception.

Remove prompt statement (no_prompt)

JavaScript’s prompt function is widely considered to be obtrusive as UI elements and should be replaced by a more appropriate custom UI implementation.

Prototype methods ⇒ Object.prototype methods (no_prototype_builtins)

Call hasOwnProperty, isPrototypeOf, propertyIsEnumerable methods only from Object.prototype.
Otherwise it can cause errors.

Hoist assignment out of return statement (no_return_assign)

This rule hoists the assignments out of return. Does not apply when assignment is wrapped in parentheses.

Rewrite throw "Err" ⇒ throw new Error("Err") (no_throw_literal)

It is a good practice to throw Error objects on exceptions because they automatically keep track of where they were created.

Rewrite !key in col ⇒ !(key in col) (no_unsafe_negation)

Negates key instead of the entire expression, which is likely a bug.

Yoda conditions not (no_yoda_conditions)

Prefer natural language style conditions in favour of Yoda style conditions.

Rewrite === NaN ⇒ isNaN (prefer_is_nan)

Convert comparisons to NaN (e.g., x == NaN) to use isNaN (e.g., isNaN(x)).

⇒ self-closing JSX tags (prefer_self_closing_tag_jsx)

Components without children can be self-closed to avoid unnecessary extra closing tag.

Rewrite Function.prototype.method = ⇒ es6 class (proto_to_class)

Older code often uses the function prototype to create "classes" out of functions. This upgrades those to ES6 class syntax.

Remove unsafe params from serialize-javascript (remove-unsafe-params-from-serialize-javascript)

serialize-javascript used with unsafe parameter, this could be vulnerable to XSS.

Remove .escapeMarkup = false (remove_escape_markup)

Some template engines allow disabling HTML escaping, which can allow XSS vulnerabilities.

Remove noAssert from Buffer calls (remove_node_buffer_offset_check_flag)

If the noAssert flag is set, offset can go beyond the end of the Buffer, which is a security vulnerability.

Rewrite shouldComponentUpdate ⇒ . (remove_should_component_update_from_pure_components)

Remove the shouldComponentUpdate method from PureComponent. PureComponent already has an implementation.

Replace zlib.deflate ⇒ zlib.deflateSync (replace-zlib-deflate-to-zlib-deflateSync)

Creating and using a large number of zlib objects simultaneously can cause significant memory fragmentation. It is strongly recommended that the results of compression operations be cached or made synchronous to avoid duplication of effort

Rewrite replaceAll ⇒ replace when have regex pattern (replaceAll_to_replace)

Replaces replaceAll with replace, when have regex pattern.

Replace wildcard imports (replace_wildcard_imports)

Replace wildcard imports with explicit imports.

Split tRPC Router (split_trpc_router)

Split a tRPC router into multiple files, one per route.

test_scope_shadow (test_scope_shadow)

This tests the shadows_identifier pattern by finding all cases where a variable is shadowed.

Remove unused imports (unused_imports)

This pattern removes unused imports of top level modules like import React from "react" or import * as lodash from "lodash".

Blocks function (use_blocks)

The group_blocks function takes a target list and returns a list of lists, where each sublist is a block of items that are adjacent to each other in the original program.

Rewrite Math.pow ⇒ ** (use_exponentiation_operator)

ES7 introduced the exponentiation operator ** so that using Math.pow is no longer necessary.

Find useless ternary operator (useless-ternary-operator)

If $condition ? $answer:$answer then this expression returns $answer. This is probably a human error

Literals (util_literal)

Utility patterns for matching literals.

Upsert (util_upsert)

The upsert pattern can be used to update a value in an object, or insert it if the key doesn't already exist.

Warning for hardcoded github token (warning-for-hardcoded-github-token)

Avoid hard-coding secrets, such as credentials and sensitive data, directly into your application's source code. This practice poses a security risk as the information may be inadvertently leaked.

* Patterns with an asterisk are in private alpha with select customers.