React Best Practices

awedis - May 3 '21 - - Dev Community

In this article, I want to share some details to take care of, which will make us better React developers


Separate logic from JSX
  • It's always good to spread the logic (or functional part) from the JSX, the code will be cleaner and more editable, check the example below how to handle an onClick event instead of putting it directly inside the element
import React from 'react';

function Todo() {
  let condition = true;

  const addHandler = () => {
    if (condition) {
      //do api call
    }
  }

  return (
    <div>
      <button
        onClick={() => addHandler()}
      >Add</button>
    </div>
  )
}

export default Todo;
Enter fullscreen mode Exit fullscreen mode
Split into small components & make them reusable
  • In this part let's try to split a UI component from a real project c5781d72c1298dc869b74702b4ee42a0
  1. NavBar: Top navbar container which contains the HamBtn
  2. HamBtn: The 3 horizontal lines button, that can be used in other parts
  3. TodoRow: Todo row, containing the text, and other action buttons
  4. RadioBtn: Toggle button
  5. DeleteBtn: Delete button for todo
  6. Button: Generic button component with several dynamic props
  7. Container: The whole container for the Todo list.

All these will be separate components, this will help us in the long run, if the project becomes bigger almost all the components can be reused 😎

State Management (Redux or Context)
  • In the case of using Redux Library, I highly recommend using Sagas which will help you to make async API calls
    Redux: Perfect for larger applications where there are high-frequency state updates

  • And for Context Api, its much simple than the Redux, and you don't need to download any library
    Context API: Resourceful and ideal for small applications where state changes are minimal

Hooks and Functional Components
  • No more "this"
  • Fewer lines of code
  • It's easier to debug, test & refactor it

I think the majority of developers are already using all their projects based on these two, but I just wanted to mention it 😁

Styled-Components
  • Styled-Components is one of the new ways to use CSS in modern JavaScript
  • It is meant to be a successor of CSS Modules, a way to write CSS that's scoped to a single component, and not leak to any other element on the page
import React from 'react';
import { Text } from './SubTitle.styled';

function SubTitle() {
  return (
    <Text>Hello</Text>
  )
}
export default SubTitle;
Enter fullscreen mode Exit fullscreen mode
import styled from "styled-components";

export const Text = styled.span`
  color: #AAA;
  font-size: 20px;
`;
Enter fullscreen mode Exit fullscreen mode
Testing
  • Unit Testing - (to check a single component of an application, for more critical functions)
  • Integration Testing - (to check if different pieces of the modules are working together)
  • End-to-End Testing - (involves testing an application's workflow from beginning to end, aims to replicate real user scenarios)
Typescript

TypeScript is a “typed superset of JavaScript that compiles to plain JavaScript.”

Using Typescript in React will help you to develop more stable components, that are strongly typed and are faster to be integrated, lets check the simplest example

interface Props {
  label: string;
  onClick: () => void;
}
Enter fullscreen mode Exit fullscreen mode
function Button({ label, onClick, ...props }: Props) {
  return (
    <button
      onClick={onClick}
      {...props}
    >
      {label}
    </button>
  )
}

export default Button;
Enter fullscreen mode Exit fullscreen mode

12345

Intrinsic elements:
Intrinsic elements are looked up on the special interface JSX.IntrinsicElements. By default, if this interface is not specified, then anything goes and intrinsic elements will not be type checked. However, if this interface is present, then the name of the intrinsic element is looked up as a property on the JSX.IntrinsicElements interface.

Intrinsic elements will allow us to use the native 'props' of an element

export type Props = JSX.IntrinsicElements["button"] & {
  label: string;
}
Enter fullscreen mode Exit fullscreen mode
<Button
  label={'SUBMIT'}
  onClick={() => console.log('CLICK')}
  onBlur={() => console.log('BLUR')}
/>
Enter fullscreen mode Exit fullscreen mode

React is an awesome library, you can split & organize your code in a way to become very flexible & scalable, wanted to keep it simple & high-level

Wish it was helpful and that's it 😊

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player