The Talent500 Blog
3 useful tips to clean up your React component types 1

3 useful tips to clean up your React component types

React is created by Facebook to allow developers to have control over all the functions of JavaScript and have the freedom to code in any style. However, developers must follow some common patterns and conventions for reusability and maintainability. Writing clean React component code is a standardizing technique for a unified project structure.

React Components are independent and reusable bits of code that help make the code much more concise. They are similar to JavaScript functions, the only difference being that they work in isolation and return HTML. As a React developer, you will use the React component library often to write code faster and more efficiently.

This post looks at some of the best practices for writing clean React component types.

1. Write React components in TypeScript

TypeScript offers a type interface allowing developers to write better code without worrying about explicitly defining each variable type. It is the property of TypeScript to infer the style of the variable from its value. In the context of a React component, it can be used to write code without explicitly defining the variable type in the codebase. It helps clean up the component codebase.

Here is an example of how TypeScript can infer the return type of the React components without explicitly defining it; the resulting code is cleaner.

// Letting TypeScript inferring the type: (props: MyProps) => JSX.Element

const MyComponent = (props: MyProps) => <div>beep</div>;

// Explicitly defining a return type (3 similar options of writing the same as above)

const MyComponent = (props: MyProps): ReactElement => <div>boop</div>;

const MyComponent = (props: MyProps): JSX.Element => <div>boop</div>;

const MyComponent: FC<MyProps> = (props) => <div>boop</div>;

Some developers argue that using TypeScript to allow React component code to infer the return type can be risky. It is possible in more dynamic systems, so it is advised to check the inferred type to avoid making mistakes.

Since the release of React hooks in version 16.8, components can be written as functions because you can get the same functionality with much less code. The React.FC type from the @types/react package is used to mark a function as a component.

2. Use maps over if/else

When creating React components try to use maps over if/else statements wherever possible. The if/else statements create nesting within the code that makes the codebase challenging to read or maintain.

React component code can be greatly simplified with maps, and nesting can be avoided. Here is an example of a component using if/else:

const Student = ({ name }) => <p>Student name: {name}</p>

const Teacher = ({ name }) => <p>Teacher name: {name}</p>

const Guardian = ({ name }) => <p>Guardian name: {name}</p>

export default function SampleComponent({ user }) {

   let Component = Student;

   if (user.type === ‘teacher’) {

     Component = Teacher

   } else if (user.type === ‘guardian’) {

     Component = Guardian

   }

 return (

     <div>

      <Component name={user.name} />

     </div>

   )

}

The same React component when written using maps, the complexity of the code eases. Here’s how:

import React from ‘react’

const Student = ({ name }) => <p>Student name: {name}</p>

const Teacher = ({ name }) => <p>Teacher name: {name}</p>

const Guardian = ({ name }) => <p>Guardian name: {name}</p>

const COMPONENT_MAP = {

   student: Student,

   teacher: Teacher,

   Guardian: Guardian

}

export default function SampleComponent({ user }) {

   const Component = COMPONENT_MAP[user.type]

return (

     <div>

      <Component name={user.name} />

     </div>

   )

}

When you use maps, the components become more declarative and much easier for any developer to comprehend. Furthermore, it makes it easy to extend the logic or add more items to it.

3. Split larger components 

One of the best ways to write cleaner React components is to use the ‘separation of concern‘ method to split more significant components. In the context of React components, the separation of concern implies separating the parts of the components responsible for displaying the element tree from the ones responsible for fetching and mutating the data.

The hooks were introduced in React to facilitate separation of concern and allow developers to write cleaner code. In practical applications, it is used for wrapping the logic that manages API calls or global state connections with a custom hook.

Here’s an example of React component:

import React from ‘react’

import { someAPICall } from ‘./API’

import ItemDisplay from ‘./ItemDisplay’

export default function SampleComponent() {

   const [data, setData] = useState([])

useEffect(() => {

    someAPICall().then((result) => {

      setData(result)

     })

   }, [])

function handleDelete() {

    console.log(‘Delete!’);

   }

function handleAdd() {

    console.log(‘Add!’);

   }

const handleEdit = () => {

    console.log(‘Edit!’);

   };

return (

     <div>

      <div>

        {data.map(item => <ItemDisplay item={item} />)}

      </div>

<div>

        <button onClick={handleDelete} />

        <button onClick={handleAdd} />

        <button onClick={handleEdit} />

      </div>

     </div>

   )

}

Now, the same component is refactored with the code split using custom hooks:

import React from ‘react’

import ItemDisplay from ‘./ItemDisplay’

export default function SampleComponent() {

   const { data, handleDelete, handleEdit, handleAdd } = useCustomHook()

return (

     <div>

      <div>

        {data.map(item => <ItemDisplay item={item} />)}

      </div>

      <div>

        <button onClick={handleDelete} />

        <button onClick={handleAdd} />

        <button onClick={handleEdit} />

      </div>

     </div>

   )

}

Conclusion

As a React developer, understanding the ways of creating clean components enable you to write cleaner, readable, and maintainable code. It is one of the qualities we use to vet React developers when they join Talent500. For more React developer resources, check out this React developer toolkit.

We are a global remote team building platform startups, and Fortune 500 companies use. If you want to explore opportunities, join us here.

 

 

0
Manik Sharma

Manik Sharma

Manik Sharma specializes primarily in UI or Software Development using Javascript libraries like React and Redux along with HTML, CSS, and other libraries like Bootstrap, Node.js, Express.js, MongoDB. He loves to talk business and think of cool startup ideas. Definitely, an entrepreneur in making. He is equally interested in discussing innovative ideas that can make a huge difference in someone's life.

Add comment