boolean-prop-naming
button-has-type
default-props-match-prop-types
defaultProps
and propTypes
, encouraging developers to explicitly declare props that have defaults, thereby improving code readability and maintainability. This rule helps prevent cases where defaultProps
are defined for props that are not declared in propTypes
, which can lead to confusion about the expected props for a component.destructuring-assignment
this.props
or this.state
multiple times, which not only makes the code cleaner but also potentially reduces the size of the compiled code.this.props
or this.state
, especially in deeply nested structures.display-name
forbid-component-props
className
on a CustomButton
component encourages using a designated prop like variant
for styling variations, aligning with design systems and component libraries.
className
or style
, which can lead to diverse implementations and make the codebase harder to maintain, it requires developers to use more descriptive props such as variant
. This specificity can make the code easier to understand and maintain over time.
dangerouslySetInnerHTML
on components directly can mitigate the risk of cross-site scripting (XSS) attacks by encouraging the use of safer alternatives or patterns to accomplish similar functionality.
forbid-dom-props
style
prop) or direct manipulation of certain attributes that might lead to security vulnerabilities, such as innerHTML
, enhancing both the maintainability and security of the code.forbid-elements
forbid-foreign-prop-types
forbid-prop-types
propTypes
rather than generic types like any
, object
, or array
, which improves the component’s prop validation, making it clearer to other developers what type of data should be passed to a component. For instance, using PropTypes.shape
instead of PropTypes.object
provides a detailed structure of the expected prop.
PropTypes.any
with PropTypes.number
explicitly states the expected type, removing ambiguity and potential misuse of the component.
function-component-definition
this
keyword misuse, as arrow functions do not have their own this
context, which aligns well with the functional component paradigm in React.hook-use-state
iframe-missing-sandbox
React.createElement
. This comprehensive approach ensures that all iframes, irrespective of their creation method, are evaluated, leaving no room for inadvertently omitting the sandbox attribute in dynamically generated content.
index
Button
component is imported without digging into the components
directory structure.components
directory. By specifying the exact file, developers can ensure they are importing the correct Button
component.jsx-boolean-value
true
. Specifically, it can automate the removal or addition of ={true}
for boolean attributes depending on the chosen configuration (ALWAYS
or NEVER
), making the codebase more uniform.
<MyComponent isEnabled />
is easier and quicker to read and understand than <MyComponent isEnabled={true} />
, especially in larger components or when multiple boolean props are involved.
true
) has a different effect than explicitly setting it to true
, or vice versa. Standardizing this aspect across the project helps avoid such confusion.
jsx-child-element-spacing
jsx-closing-bracket-location
jsx-closing-tag-location
jsx-curly-brace-presence
jsx-curly-newline
jsx-curly-spacing
jsx-equals-spacing
jsx-filename-extension
as-needed
option). This flexibility allows for a stricter enforcement in projects where JSX is not ubiquitous, ensuring that developers only use the JSX-specific extensions for files that actually contain JSX, promoting cleaner and more semantically meaningful file naming in the codebase.
jsx-first-prop-new-line
jsx-fragments
<React.Fragment>...</React.Fragment>
) to the shorthand version (<>...</>
) or vice versa, depending on the configuration. This automated fixing helps in maintaining consistency with minimal manual effort.jsx-handler-names
jsx-indent-props
jsx-indent
jsx-key
key
props in iterators/collection literals.map()
function) have a key
prop assigned. This is crucial for React’s rendering algorithm to accurately track changes in lists of elements, helping prevent unnecessary re-renders and potential bugs related to element identity.
key
prop in JSX elements and fragments generated in iterators, the rule aids in maintaining the performance optimization benefits that keys provide in React applications. Without keys, React cannot efficiently re-order elements in the DOM during updates, leading to degraded app performance.
key
prop in relation to spread attributes within JSX elements. This ensures that explicit key props are correctly recognized and not unintentionally overwritten by spread operations, which can be crucial for maintaining the intended behavior of component lists.
jsx-max-depth
jsx-max-props-per-line
jsx-newline
jsx-no-bind
.bind()
or arrow functions in JSX props.bind()
in JSX props which can help in avoiding unnecessary function re-creations during component re-render cycles. When a function is bound within a JSX prop, it gets re-created on every render, leading to performance degradation over time, especially in large and complex component trees.this
context without needing to be bound in the render method or constructor, thereby promoting cleaner and more readable code.this
. Inline arrow functions create a new instance of the function each time the component re-renders, which could lead to unexpected behaviors in certain scenarios, especially when the functions are used as props for pure components or within shouldComponentUpdate lifecycle methods.jsx-no-comment-textnodes
// comment
) within text nodes in JSX, which can lead to visual clutter in the rendered output or potentially expose comments to end-users that were intended to remain in the codebase.{/* comment */}
) for inserting comments within JSX elements, ensuring that the comments do not mistakenly become part of the UI displayed to the user.jsx-no-constructed-context-values
useMemo
and useCallback
hooks for optimizing context values, thereby promoting more efficient memory usage and preventing the creation of new functions and objects on each render.jsx-no-duplicate-props
ignoreCase
configuration, it provides flexibility in enforcing conventions in a codebase that might have varying case sensitivity practices, hence reducing potential for error due to oversight in case differences.jsx-no-leaked-render
false
, null
, undefined
, 0
, ''
etc.) in JSX, which can lead to unexpected and often undesired visual outcomes in a React application. For instance, rendering 0
or an empty string directly can be a common mistake when using logical operators for conditional rendering.ternary operators
) over logical &&
operators for conditional rendering in JSX. This ensures that developers explicitly handle the cases where the condition fails, leading to clearer and more intentional render paths rather than relying on JavaScript’s coercion rules.jsx-no-literals
jsx-no-script-url
javascript:
URLsjavascript:
URLs can open up the application to cross-site scripting (XSS) attacks, where malicious scripts are executed in the context of the user’s browser. This rule helps in identifying such potentially dangerous URLs in JSX attributes and discouraging their use, thereby reducing the risk of XSS vulnerabilities.
javascript:
URLs, this rule promotes safer and more secure coding practices among developers. It encourages the use of alternative methods for event handling or executing JavaScript code without embedding it directly in URLs, which is a more secure approach to web development.
javascript:
URLs for functionality can be harder to debug and maintain, especially when such URLs are used as a workaround for implementing event handlers or other logic. This rule helps maintain a cleaner codebase by enforcing the use of proper event handling mechanisms provided by React, making the code easier to understand and maintain.
javascript:
URLs, this rule indirectly contributes to the overall security posture of the application. It ensures that developers are not inadvertently introducing security flaws through the use of such URLs, which could be exploited by attackers to compromise the application or the data it handles.
jsx-no-target-blank
target="_blank"
attribute without rel="noreferrer"
target="_blank"
in anchor tags by ensuring that rel="noreferrer"
is present. This prevents the new page from accessing the originating page’s window object, which can protect from certain types of phishing attacks or malicious scripts.rel="noreferrer"
when target="_blank"
is used, promoting safer web development habits without developers needing to remember to add this attribute manually.rel="noopener"
instead of noreferrer
if needed for analytics purposes, providing flexibility while still maintaining security.jsx-no-undef
jsx-no-useless-fragment
jsx-one-expression-per-line
{' '}
) are required to maintain desired whitespace in the rendered output.jsx-pascal-case
allowAllCaps
, allowLeadingUnderscore
, and allowNamespace
, it provides flexibility to accommodate various coding styles and project-specific naming conventions without compromising the overall goal of maintaining a consistent naming scheme.ignore
option) allows teams to progressively adopt this naming convention without having to refactor existing components immediately, thus providing a smoother transition path.jsx-props-no-multi-spaces
jsx-props-no-spreading
jsx-sort-default-props
defaultProps
declarations makes it easier for developers to read and understand the default props being passed to a component. When props are organized, developers can quickly locate a specific prop without having to search through an unsorted list, improving code readability and maintainability.
defaultProps
declarations follow a consistent order throughout the project. This uniformity helps in standardizing code practices across the codebase, making the code easier to follow for new developers or contributors.
defaultProps
sorted, the likelihood of these conflicts is reduced as developers will be adding new props in a predetermined order.
defaultProps
. This automation saves developers time during code reviews and manual testing by ensuring that the sorting order complies with the established coding standards, without requiring manual intervention.
jsx-sort-props
ignoreCase
, callbacksLast
, shorthandFirst/Last
, and multiline
handling allow for flexibility in adopting the rule based on the team’s coding standards, accommodating varied preferences in prop ordering.jsx-space-before-closing
react/jsx-tag-spacing
, this rule provides precise control over spaces before the closing bracket of self-closing JSX tags. For projects not yet updated to use the recommended rule, it offers a way to maintain stylistic consistency and gradually transition to the newer rule without immediately overhauling existing code conventions.jsx-tag-spacing
afterOpening
, beforeSelfClosing
, etc.), allowing teams to adopt a style that best suits their project’s needs. This flexibility means teams can enforce a consistent style across their project while still adhering to their specific coding standards or preferences.jsx-uses-react
jsx-uses-vars
jsx-wrap-multilines
no-access-state-in-setstate
this.state
directly within setState
can lead to unpredictable state updates when there are multiple setState
calls in a batch. This rule promotes using a function that receives the previous state, ensuring updates are applied synchronously and based on the most recent state.
this.state
inside setState
could cause closures over the state value at the time of an asynchronous operation’s initiation, rather than its execution, leading to potential bugs or outdated state references. The rule encourages a pattern that mitigates this risk.
this.state
within setState
, it encourages the use of patterns like functional updates. This can lead to better performance in some scenarios by avoiding unnecessary re-renders or calculations based on stale state.
no-adjacent-inline-elements
no-array-index-key
react/no-array-index-key
, specifically discourages the use of array indices as keys in React elements, which is a significant practice to prevent potential issues with element reordering. Using indices as keys can lead to performance degradation and unexpected behavior in dynamic lists where the order of items might change, as React relies on keys to identify which items have changed, been added, or been removed.
todos.map((todo, index) => <li key={index}>{todo.text}</li>);
which is highlighted as a bad practice. The rule provides a corrective suggestion to use unique identifiers (<li key={todo.id}>{todo.text}</li>
) instead, making it easier for developers to adhere to best practices without manually reviewing every list rendering operation.
map
, including every
, filter
, find
, findIndex
, flatMap
, forEach
, reduce
, reduceRight
, and some
, covering almost all use cases where developers might be tempted to use array indices as keys. This comprehensive approach ensures that the best practice is enforced consistently across different scenarios and code patterns, thereby maintaining the integrity and performance of React applications.
no-arrow-function-lifecycle
this
binding. Arrow functions lexically bind this
, which might not always behave as expected within React lifecycle methods, especially if developers attempt to override them or use them in less conventional ways.
no-children-prop
React.createElement
, rather than as a direct prop. This aligns with React’s design philosophy and improves code readability, making it easier to understand the components’ structure at a glance.
no-danger-with-children
no-danger
dangerouslySetInnerHTML
, a known React property that can insert raw HTML into the DOM, potentially exposing the application to cross-site scripting (XSS) attacks if not properly sanitized.dangerouslySetInnerHTML
, the rule encourages developers to find safer alternatives for inserting content into the DOM, such as directly using JSX or other React-safe methods.no-deprecated
no-did-mount-set-state
setState
calls are not made immediately within componentDidMount
, which can lead to potential issues such as unnecessary re-renders or negatively impacting performance. Immediate state updates in componentDidMount
can cause an additional rendering phase before the browser updates the screen, potentially leading to visible flickering or increased load times.
componentDidMount
, under certain configurations (allow-in-func
mode), allowing for more flexibility in cases where state updates need to be made after asynchronous operations (like data fetching) that are initiated in componentDidMount
. This encourages developers to structure their code in a way that clearly separates immediate execution from asynchronous execution, improving code readability and maintainability.
setState
directly in componentDidMount
, it naturally steers developers towards using newer lifecycle methods or hooks (such as componentDidUpdate
, or the useEffect
hook in functional components) for managing state updates in response to prop changes or as a result of asynchronous operations. This promotes the use of newer, more efficient practices in React development, contributing to overall application performance and maintainability.
no-did-update-set-state
setState
within componentDidUpdate
can lead to an infinite loop. Since componentDidUpdate
is called after the component updates and setState
triggers an update, this rule helps prevent potential infinite rendering cycles that could arise from this pattern.
setState
within componentDidUpdate
, developers are encouraged to find safer lifecycle methods or patterns for state updates, such as getDerivedStateFromProps
, which is called before rendering.
setState
in componentDidUpdate
can lead to sluggish performance and a poor user experience. This rule aids in preemptively addressing such performance issues.
no-direct-mutation-state
setState()
for state updates, as recommended by this rule, ensures that the component gets properly re-rendered. When you mutate the state directly, React may not recognize the change, and thus the component might not re-render, leading to stale or incorrect UI.setState()
in a functional form whenever the new state is derived from the previous state. This adherence promotes more predictable state transitions and safer asynchronous state updates.no-find-dom-node
findDOMNode
, a method discouraged by React for being less efficient and more escape-hatch-like, which can lead to brittle code. React recommends using refs instead for directly accessing DOM elements, as illustrated in the rule’s fix example.findDOMNode
, this rule helps in preparing the codebase for future React updates and potential removal of findDOMNode
from the React API, thereby future-proofing the application and reducing the risk of encountering breaking changes in React upgrades.findDOMNode
can lead to suboptimal performance in React applications. By pushing towards ref usage, it ensures a more declarative way of accessing DOM elements that is better optimized by React, hence potentially enhancing the app’s performance.no-invalid-html-attribute
createElement
calls, aiding in the development of valid HTML and improving compatibility across web browsers. For instance, enforcing the use of className
over class
in JSX to align with React’s naming conventions, as highlighted in the provided example.
no-is-mounted
isMounted
because using it can lead to memory leaks and performance issues. React does not clean up the component references after unmounting if isMounted()
is used, which prevents the components from being garbage collected._isMounted
flag), developers are more aware of the lifecycle events and how they impact the component’s behavior, leading to more reliable and maintainable code.isMounted
to check component’s mount state before calling setState
, there’s a risk that the component gets unmounted before the asynchronous operation completes, potentially causing React to throw warnings or errors. Updating the state based on a manually managed flag (_isMounted
) mitigates this risk.isMounted
follows React’s recommendations. React’s team has deprecated isMounted
due to its issues and encourages developers to write components that can safely perform asynchronous operations without relying on such checks, leading to cleaner, safer code.no-multi-comp
no-namespace
no-object-type-as-default-prop
no-redundant-should-component-update
shouldComponentUpdate
in components extending React.PureComponent
is redundant since PureComponent
automatically implements a shallow props and state comparison. This rule helps maintain the intended efficiency gains of using PureComponent
.shouldComponentUpdate
in PureComponent
, it prevents developers from inadvertently implementing deep comparison logic that could negate the performance benefits of shallow comparison, leading to unnecessary re-renders.shouldComponentUpdate
methods can introduce errors in update logic, especially when used in PureComponent
, where updates are expected to be managed automatically based on shallow prop and state comparison. This rule helps reduce the likelihood of such bugs.shouldComponentUpdate
method for optimization, it suggests they might actually need a React.Component
instead of a React.PureComponent
, thereby promoting a better understanding of React’s component model and its optimization mechanisms.no-render-return-value
ReactDOM.render
return value, which is contrary to the React paradigm of handling components. React’s component model is designed to be declarative and to manage the lifecycle and state of components internally, without requiring the user to interact with or store references to the rendered component instances.ReactDOM.render
changed from a reference to the component to void
. This rule ensures that developers do not rely on deprecated behavior that could break their applications in future React versions.createRef
API for accessing DOM nodes or React elements, aligning with React’s focus on unidirectional data flow and component encapsulation. This improves code maintainability and readability, as it keeps the component interactions within the React ecosystem rather than relying on direct DOM manipulations or references.ReactDOM.render
. This consistency is crucial in larger projects where different developers might interact with DOM elements or React components, as it reduces the likelihood of bugs introduced by misunderstanding the return values of React’s rendering mechanism.no-set-state
setState
, it nudges developers towards using useState
, which simplifies state management in functional components.
setState
in class components, such as state updates relying on the previous state not accounting for these updates being batched. Using hooks like useState
offers a more direct way to update state, potentially reducing bugs related to state management.
no-string-refs
createRef
API instead encourages a more modern, safer approach to React refs that is less prone to errors and more consistent with React’s current best practices.
React.createRef
gives React a clearer understanding of the ref’s usage, potentially allowing for more efficient rendering and updates. String refs, being more opaque, could hinder certain optimizations or static analysis efforts.
no-this-in-sfc
this
from being used in stateless functional componentsthis
in a scope where it is undefined, which is critical in avoiding runtime errors in Stateless Functional Components (SFCs).this
in SFCs, the rule enforces the proper use of props and state passing mechanisms in functional components, which improves code readability and maintainability by making data flow more explicit and predictable.this
aren’t concerned with the component context (this) bindings, potentially leading to less memory usage and faster execution times due to the optimal use of functional component characteristics.no-typos
propTypes
property on React components, making it easier for new developers to follow best practices and established patterns without confusion.no-unescaped-entities
<
character. This immediate feedback loop aids developers in learning and applying best practices for HTML entity handling in React applications, contributing to the overall robustness and security of the application.
no-unknown-property
class
should be corrected to className
, highlighting a common mistake due to HTML and JSX syntax differences.
autofocus
is incorrectly used instead of the standard autoFocus
in JSX, this rule can automatically suggest or apply the correct property name, thereby enhancing code quality with minimal manual intervention.
no-unsafe
no-unstable-nested-components
no-unused-class-component-methods
no-unused-prop-types
propTypes
that are never used in the component, which can lead to confusion and makes the code harder to maintain by leaving artifacts from past implementations or features that were considered but never actually used.propTypes
, it helps in identifying potentially unused or unnecessary data passed to components, which might indicate overly complicated component interfaces or unused data fetching, thus potentially leading to simplification of component APIs or reducing unnecessary data fetching and state management complexity.no-unused-state
react/no-unused-state
rule efficiently identifies state properties in React components that are declared but never actually used in rendering or logic, helping developers to avoid keeping dead code in their codebase, which can lead to confusion and maintenance issues over time.no-will-update-set-state
componentWillUpdate
, advising against using setState
within it because doing so can lead to unexpected behavior in the component’s update lifecycle. This ensures components behave predictably when their state or props change.
setState
in componentWillUpdate
, the rule implicitly guides developers towards more appropriate lifecycle methods for state updates, such as componentDidUpdate
, which is the recommended method for responding to prop changes after a render has occurred. This promotes best practices within React development.
componentWillUpdate
, as it might lead to additional re-rendering cycles that are unnecessary or unintended. Preventing this practice helps in maintaining the application’s performance and responsiveness.
setState
in a lifecycle method that is considered unsafe and is deprecated in newer versions of React. This aligns with React’s move towards safer and more predictable update patterns, such as those encouraged by hooks and functional components.
prefer-es6-class
React.createClass
method when the configuration is set to always
. This ensures that all components across a project adhere to the modern class syntax, promoting readability and maintainability.
React.createClass
vs. ES6 classes). This immediate feedback can help prevent the mixture of different component styles within a codebase, reducing the cognitive load on developers who need to understand or refactor the code.
prefer-exact-props
prefer-read-only-props
readonly
, the rule implicitly prompts developers to design components with clear input/output contracts. This fosters better component encapsulation and promotes the composition of components, as each component is less concerned with internal state changes of its children and more focused on how to compose them based on their props.prefer-stateless-function
prop-types
react-in-jsx-scope
React.createElement
calls, and without React being imported, these calls will fail.require-default-props
require-optimization
shouldComponentUpdate
, developers are encouraged to consider when their components actually need to re-render. This can prevent unnecessary renders, improving the performance of React applications, especially in complex UIs or applications with frequent state updates.
shouldComponentUpdate
forces developers to think critically about their component’s dependencies and when updates should occur. This leads to more efficient and purposeful code, as developers must explicitly define the conditions under which a re-render is necessary, rather than relying on React’s default behavior.
shouldComponentUpdate
introduces them to the component lifecycle method earlier. This awareness can lead to better debugging skills, as understanding when and why a component updates is crucial for diagnosing rendering issues and optimizing component performance.
require-render-return
self-closing-comp
react/self-closing-comp
ESLint rule enforces cleaner and more concise code by eliminating unnecessary closing tags for components that don’t contain children. This leads to easier-to-read and more maintainable code, specifically improving the readability of JSX structures in React applications.sort-comp
sort-default-props
defaultProps
, making it easier for developers to locate and read prop definitions by adhering to a predictable structure. This is particularly beneficial in components with a large number of props.defaultProps
declarations, as reviewers can quickly verify the order without having to search through unsorted object properties.sort-prop-types
requiredFirst
, callbacksLast
, and ignoreCase
, allowing for more nuanced and flexible sorting that can align with a team’s or project’s specific coding standards. This adaptability ensures that the sorting logic can cater to different preferences and requirements, such as prioritizing required properties or grouping callback functions.
state-in-constructor
always
in the constructor vs. never
as a class property), the rule can help prevent potential issues related to the timing of state initialization. In some cases, initializing state outside of the constructor might lead to unexpected behaviors, especially when the state depends on props or needs to be set based on some conditions that are only available in the constructor.
static-property-placement
propTypes
and defaultProps
, are positioned in the same manner across multiple components. This makes the code easier to read and maintain, especially in larger projects where consistency in code structure is crucial for efficient teamwork.
style-prop-object
style
prop, making it easier to read and maintain styles across the project.style
prop in JSX elements.void-dom-elements-no-children
<img />
, <br />
) from receiving children<img />
and <br />
, which enhances code quality and adheres to web standards.