← All posts
Daniel Strong Monday, December 19, 2022

Enforce React Best Practices

Share

AUTHOR

Daniel Strong, Frontend Engineer

Daniel is a Frontend Engineer at Codiga.

He is a passionate frontend engineer, teacher, and learner. He has worked on or led several creative projects where he's grown his leadership, management, design, and programming skills.

See all articles

React is a powerful JavaScript library for building user interfaces, and it's no wonder it has become one of the most popular choices for web development. However, with great power comes great responsibility, and it's essential to follow best practices to ensure your React applications are performant and maintainable.

In this post, we'll delve into some custom rules recently created on Codiga for React best practices that you can use to catch issues and potentially fix them with multiple options.

React Best Practices Ruleset

React Rule: boolean-naming

In React, a boolean value is a variable that can only be either true or false. Boolean variables are typically used to enable or disable a particular feature or behavior in a component.

Boolean variables are usually named with a prefix of "is", "has", or "can" to indicate that they are boolean values. For example, a component might have a boolean variable named isDisabled that is used to enable or disable the component or a boolean variable named canSubmit that is used to determine whether a form can be submitted.

// good
const isDisabled = true;
const hasAccess = false;
const canEdit = true;

// bad
const disabled = true;
const noAccess = false;
const editable = true;

Following this best practice by naming your variables in this manner dramatically enhances your code maintainability and readability for others. Test this rule on our Codiga Hub to see how we suggest fixes depending on your code.

React Rule: max-params-function-def

As the examples below show, Javascript functions can accept any number of parameters from zero onwards.

// no parameters
function myFunction() {}

// five parameters
function myFunction(param1, param2, param3, param4, param5) {}

When you give your parameters proper names and default values, your code becomes more difficult to understand and use as your parameter count grows.

This rule enforces a maximum of four parameters which is considered a best practice. If you genuinely need more, we suggest splitting the function into smaller chunks or perhaps using an object parameter that is easier to maintain.

// one parameter
function myFunction({ param1, param2, param3, param4, param5 }) {}

React Rule: no-children-prop

Passing children as a prop is generally not recommended in React because it can lead to problems with the component's reusability and maintainability.

One issue with passing children as a prop in React is that it can make it more challenging to understand the structure and intent of the component. When children are given as a prop in React, they are just a raw piece of data passed along with the other props to the component. This can make it harder to understand the component's purpose and how it is intended to be used.

Another issue with passing children as a prop in React is that it can make it more difficult to reuse the component. For example, if you want to use the same component in multiple places but with different children, you would need to pass the children as a prop each time. This can make the component less flexible and harder to work with.

Instead of passing children as a prop, it is considered best practice to use the children prop that is automatically provided by React, which this rule checks.

function MyComponent(props) {
  return (
    <div>
      <h3>MyComponent Header</h3>
      {props.children}
    </div>
  );
}

function App() {
  return (
    <MyComponent>
      <p>
        This is some content that will be passed as children to MyComponent.
      </p>
    </MyComponent>
  );
}

React Rule: no-target-blank

Using the target="_blank" attribute in links (a elements) is generally not recommended because it can lead to security and usability issues.

One security issue with target="_blank" is that it can allow an attacker to open a link in a new window or tab and then manipulate the original page, potentially leading to phishing attacks or other malicious behavior. This can be mitigated by using the rel="noopener" or rel="noreferrer" attributes in conjunction with target="_blank", but it is still a potential issue to consider.

Generally, it is best practice to use links that open in the same window or tab, unless there is a specific reason to open the link in a new window or tab. If you do need to use target="_blank", be sure also to use the rel="noopener" or rel="noreferrer" attributes to mitigate security issues.

Test this rule on our Codiga Hub to see how we provide different fixes depending on the code.

React Rule: button-has-type

In general, it is a good idea to specify the type attribute for button elements to ensure that the button behaves as expected. By explicitly specifying the type of button, you can help ensure that the button performs the intended action when clicked.

// bad - defaults to a submit action with a full page refresh on click
<button onClick={() => {}}>Click</button>

// good - no page refresh on click
<button type="button" onClick={() => {}}>Click</button>

Test this rule on the Codiga Hub to see how we provide multiple fix options depending on your code.

React Rule: hook-use-state

It is a best practice in React to name the state variable and the update function using the same base name, with set as a prefix for the update function. For example, if the state variable is count, the update function is often named setCount. This makes it clear that the update function is related to the state variable it updates.

// bad
const [count, setter] = useState(0);

// good
const [count, setCount] = useState(0);

This rule will also follow the best practice and warn you if when might not be needed or if you redeclare a variable instantly.

// if you don't need the setter, maybe this shouldn't be state
const [count] = useState(0);

// unneccessary variable redeclaration
const useCount = useState(0);

Automatically follow React best practices

To use all of these React rules consistently, all you need to do is to install the integration in your IDE (for VS Code or JetBrains) or code management system and add a codiga.yml file at the root of your profile with the following content:

rulesets:
  - react-best-practices

You can also run and test these React best practice rules within the React Best Practices ruleset on the Codiga Hub.

Feel free to copy and try them in our playground or duplicate a rule to make your own updates.

We look forward to seeing what kind of rules you can create! They don't have to be about best practices in React, so get creative and tailor them for yourself.

If you have any suggestions or feedback, don't hesitate to contact us.

More Resources

If you've ever used ESLint before, these React rules may look familiar.

Here are some links to similar rules from ESLint:

Schedule a demo

Code analyzed in seconds with Codiga Automated Code Reviews.

Write code faster with the Codiga Coding Assistant.

Let's talk!