Practical Insights into Using ChatGPT to Optimize Front-End Developement
Table of Contents

Practical Insights into Using ChatGPT to Optimize Front-End Developement

In the field of front-end development, there are certain challenges that can be resolved quickly. ChatGPT can play a vital role in speeding up this process. On one hand, junior front-end developers can easily solve problems without having to ask their mentors. On the other hand, senior frontend developers can focus on their job without any disruptions.  

There are real-life examples where ChatGPT can be used in daily front-end tasks. One of our React developers, Jakub Szewczyk, told us about his daily work with ChatGPT and how it helps him be a better programmer.  

ChatGPT Can Generate Interfaces Using Data Returned From API Request

Integrating data from external sources is a part of almost all (if not all) web apps. To ensure maximum type safety, you must generate interfaces/types from the incoming json. If the data is simple – no problem. Unfortunately (for developers) it’s not usually the case.

We can use the data from “Dummy JSON” as an example of the functionality from https://dummyjson.com/

Obraz zawierający tekst, zrzut ekranu, oprogramowanie, designOpis wygenerowany automatycznie

Let’s use ChatGPT to generate interfaces for type-safe front-ends.

Prompt:
Generate a TypeScript interface for following data:  

{

   "id": 1,

   "title": "iPhone 9",

   "description": "An apple mobile which is nothing like apple",

   "price": 549,

   "discountPercentage": 12.96,

   "rating": 4.69,

   "stock": 94,

   "brand": "Apple",

   "category": "smartphones",

   "thumbnail": "https://i.dummyjson.com/data/products/1/thumbnail.jpg",

   "images": [

       "https://i.dummyjson.com/data/products/1/1.jpg",

       "https://i.dummyjson.com/data/products/1/2.jpg",

   ]

}

Answer:

Obraz zawierający tekst, zrzut ekranu, oprogramowanie, Oprogramowanie multimedialneOpis wygenerowany automatycznie

We arrived at the correct conclusion ~20 minutes faster than if we typed everything manually. Thanks to the AI we have accurately typed data just seconds after submitting our prompt. Even though we could have been more strict with types, they are alright, and will do fine.

ChatGPT Can Help Us with Testing React Functions and Hooks

Writing tests is imperative for creating maintainable code. Even though it is not what developers might like the most, if there was only a tool to do it for us...

Prompt:
Write tests for this code:

export const firstLetterUppercase = (str: string): string => { 
	if (!str) { return ''; }  
  return str.toLowerCase()
  	.split(' ') 
    .map((word) => { 
    	return word[0].toUpperCase() + word.substring(1); 
  }) .join(' '); 
}; 

First answer:

Obraz zawierający tekst, elektronika, zrzut ekranu, oprogramowanieOpis wygenerowany automatycznie

The output isn’t the best. Let’s do some fine-tuning.

Prompt:

Test this method against null, undefined, empty string and numbers.

Second answer:

Obraz zawierający tekst, zrzut ekranu, oprogramowanie, Oprogramowanie multimedialneOpis wygenerowany automatycznie

Seems pretty good. We can copy and paste those tests to IDE and run them using Jest.

If AI does not have the correct context, we will not receive a perfect answer. Unlike humans, AI often won’t correctly come up with the information it does not have. ChatGPT can save us considerable time on writing tests, and can be more thorough than we would have been.

ChatGPT Can Speed Up the Process of Preparing Documentation for Code.

Raise your hand if your team/you ever had to work on a project with little or no documentation. Why is that? Some developers don’t like spending time documenting the code for others, because it’s time consuming, and there are seemingly no returns on the time investment. Could AI write documentation for us? Sure.

Our buddy, ChatGPT can make front-end development problem-free for us.

Prompt:

Prepare docs for the given function:  

export function mergeDirections( columns: string[], directions: ColumnDirectionModel, direction: ColumnDirectionType, ): ColumnDirectionModel { 

	const items = columns.reduce((acc: ColumnDirectionModel, column: string) =>  { 
  	acc[column] = direction; return acc; 
  }, {}); 
  return { ...directions, ...items }; 
} 

Answer:

Obraz zawierający tekst, elektronika, zrzut ekranu, oprogramowanieOpis wygenerowany automatycznie

Almost as if we wrote the documentation ourselves.

ChatGPT Can Help Us with Styling.

Tailwind is a CSS framework that allows developers to style components using HTML classes. It’s (almost) universally well-liked for the simplicity it brings, and for the customization capabilities. As a bonus, centering a div was never easier, and using ChatGPT to e.g., generate color palettes, feels like cheating.

Prompt:

Create Tailwind CSS styles for 3 centred boxes using flexbox keeping mind the RWD principles

Answer:

Obraz zawierający tekst, zrzut ekranu, oprogramowanie, Oprogramowanie multimedialneOpis wygenerowany automatycznie

There is no need to read docs when your assistant can do it faster.

We also get an explanation for why we got what we got:

Obraz zawierający tekst, zrzut ekranu, CzcionkaOpis wygenerowany automatycznie

ChatGPT Can Enhance Code Readability and Help Us Keep it KISS (Keep it Simple, Silly).

Developers sometimes write a portion of code that works, but after a few months, when they revisit those lines for updates, they encounter a repetitive cycle. Eventually, there ends up being a lot of unused code or code written in different coding styles (senior, mid, or junior developers may have worked on it). We aim to have this code segment written with the principle of KISS and make it more readable. That's when we can turn to GPT and give it a try to simplify the code and make it easier to understand.

Prompt:

This is a search box React component. Make it easier to read and remove unnecessary elements, add i18n for hardcoded texts and use Tailwind for styles:

import React, { FC, useState, useCallback } from 'react'; 

import { SearchIcon } from '../../icons'; 

import { FormControl, InputGroup } from 'react-bootstrap'; 

 

interface SearchProps { 

  onChange: () => void; 

  onReset: () => void; 

  register: any; 

  formControl?: { 

    palceholder: string; 

    ariaLabel: string; 

    ariaDescribedBy: string; 

    name: string; 

  }; 

} 

 

const searchIconStyles = { 

  display: 'flex', 

  alignItems: 'center', 

  border: '1px solid #ced4da', 

  borderRight: 0, 

  paddingLeft: '5px', 

}; 

 

const Search: FC<SearchProps> = ({ register, onChange, onReset, formControl, children }) => { 

  const [isFocused, setIsFocused] = useState(false); 

 

  const handleOnBlur = useCallback(() => { 

    setIsFocused(false); 

  }, []); 

 

  const handleOnFocus = useCallback(() => { 

    setIsFocused(true); 

  }, []); 

 

  return ( 

    <InputGroup size="sm" style={{ width: '400px' }}> 

      <InputGroup.Prepend style={{ ...searchIconStyles, borderColor: isFocused ? '#80bdff' : '#ced4da' }}> 

        <SearchIcon /> 

      </InputGroup.Prepend> 

      <FormControl 

        aria-label={formControl?.ariaLabel ?? 'Search control'} 

        aria-describedby={formControl?.ariaDescribedBy ?? 'search-control'} 

        type="text" 

        name={formControl?.name ?? 'search'} 

        ref={register} 

        onChange={onChange} 

        placeholder={formControl?.palceholder ?? 'Search'} 

        className="border-right-0 border-left-0" 

        style={{ boxShadow: 'none' }} 

        onFocus={handleOnFocus} 

        onBlur={handleOnBlur} 

      /> 

      <InputGroup.Append> 

        <InputGroup.Text 

          color="#007bff" 

          style={{ 

            cursor: 'pointer', 

            color: '#80bdff', 

            backgroundColor: 'white', 

            border: isFocused ? '1px solid #80bdff' : '1px solid #ced4da', 

          }} 

          onClick={onReset} 

        > 

          x 

        </InputGroup.Text> 

      </InputGroup.Append> 

    </InputGroup> 

  ); 

}; 

 

export default Search; 

Answer:

import React, { FC, useState, useCallback } from 'react'; 

import { useTranslation } from 'react-i18next'; 

import { SearchIcon } from '../../icons'; 

import { FormControl, InputGroup } from 'react-bootstrap'; 

 

interface SearchProps { 

  onChange: () => void; 

  onReset: () => void; 

  register: any; 

  formControl?: { 

    placeholder: string; 

    ariaLabel: string; 

    ariaDescribedBy: string; 

    name: string; 

  }; 

} 

 

const Search: FC<SearchProps> = ({ register, onChange, onReset, formControl }) => { 

  const { t } = useTranslation(); 

  const [isFocused, setIsFocused] = useState(false); 

 

  const handleOnBlur = useCallback(() => { 

    setIsFocused(false); 

  }, []); 

 

  const handleOnFocus = useCallback(() => { 

    setIsFocused(true); 

  }, []); 

 

  return ( 

    <InputGroup size="sm" className="w-64"> 

      <InputGroup.Prepend className={`flex items-center border border-gray-300 border-r-0 pl-2 ${isFocused ? 'border-blue-500' : ''}`}> 

        <SearchIcon /> 

      </InputGroup.Prepend> 

      <FormControl 

        aria-label={formControl?.ariaLabel || t('searchControl')} 

        aria-describedby={formControl?.ariaDescribedBy || 'search-control'} 

        type="text" 

        name={formControl?.name || 'search'} 

        ref={register} 

        onChange={onChange} 

        placeholder={formControl?.placeholder || t('searchPlaceholder')} 

        className="border-r-0 border-l-0 focus:outline-none focus:shadow-none" 

        onFocus={handleOnFocus} 

        onBlur={handleOnBlur} 

      /> 

      <InputGroup.Append> 

        <InputGroup.Text 

          className={`cursor-pointer ${isFocused ? 'text-blue-500 border-blue-500' : 'text-gray-500 border-gray-300'}`} 

          onClick={onReset} 

        > 

          x 

        </InputGroup.Text> 

      </InputGroup.Append> 

    </InputGroup> 

  ); 

}; 

 

export default Search; 

We can see a lot of changes made quickly.  That’s why we love ChatGPT

ChatGPT Can Explain Things to Us.

Prompt:

What is useCallback and when I should use it?

Answer:

Obraz zawierający tekst, zrzut ekranu, oprogramowanie, Oprogramowanie multimedialneOpis wygenerowany automatycznie

Obraz zawierający tekst, zrzut ekranu, Czcionka, dokumentOpis wygenerowany automatycznie

ChatGPT Can Optimize Our React Components.

Optimizing React components is sometimes a complicated process. It’s such a complicated process that Meta decided to create an experimental optimizer which its engineers are working on.

Prompt:

Optimize this part of React component code in order to get better performance:

import React, { useState } from "react"; 

 

function MyComponent({ data }) { 

  const [filter, setFilter] = useState(""); 

  const filteredData = () => { 

    // Perform some expensive filtering here 

    return data.filter((item) => item.includes(filter)); 

  }; 

 

  return ( 

    <div> 

      <input value={filter} onChange={(e) => setFilter(e.target.value)} /> 

      {filteredData.map((item) => ( 

        <div key={item}>{item}</div> 

      ))} 

    </div> 

  ); 

} 

Answer:

import React, { useState, useMemo } from 'react'; 

 

function MyComponent({ data }) { 

 

  const [filter, setFilter] = useState(''); 

  const filteredData = useMemo(() => { 

    // Perform some expensive filtering here    return data.filter(item => item.includes(filter)); 

  }, [data, filter]); 

 

  return ( 

 

    <div> 

      <input value={filter} onChange={e => setFilter(e.target.value)} /> 

      {filteredData.map((item, index) => ( 

        <div key={index}>{item}</div> 

      ))} 

    </div> 

  ); 

} 

 

You can optimize the component in a few ways:

Memoization: Rather than recomputing the filtered data on every render, you can use the useMemo hook from React. This hook ensures that your expensive computation is only run when necessary - specifically, when data or filter changes.

Key Property in the map: Make sure your key is unique. If item is not unique, you should use something else as the key, like an index or id – In my opinion we shouldn’t use index as key in children div, to avoid not needed re-renders of component, that’s why we should always double check if the ChatGPT answer is correct.

Conclusion

Before the age of AI, we had experts specializing in specific technical fields such as Frontend, Backend, Databases, and more. With the help of ChatGPT, we can transform them into ‘Generalists’ who have knowledge across many domains. All knowledge seems to be (or is) one query away.

Furthermore, we can spend less money & time on preparing PoC or MVP by using one person with ChatGPT, but also, we can increase the speed of development thanks to the use of e.g., GPT-based Copilot.

Using AI to generate perfectly optimized React code is the future of front-end development. Let’s explore that future together. Contact us to talk about your front-end needs.

Liked the article? subscribe to updates!
360° IT Check is a weekly publication where we bring you the latest and greatest in the world of tech. We cover topics like emerging technologies & frameworks, news about innovative startups, and other topics which affect the world of tech directly or indirectly.

Like what you’re reading? Make sure to subscribe to our weekly newsletter!
Relevant Expertise:
No items found.
Share

Subscribe for periodic tech i

By filling in the above fields and clicking “Subscribe”, you agree to the processing by ITMAGINATION of your personal data contained in the above form for the purposes of sending you messages in the form of newsletter subscription, in accordance with our Privacy Policy.
Thank you! Your submission has been received!
We will send you at most one email per week with our latest tech news and insights.

In the meantime, feel free to explore this page or our Resources page for eBooks, technical guides, GitHub Demos, and more!
Oops! Something went wrong while submitting the form.

Related articles

Our Partners & Certifications
© 2024 ITMAGINATION, A Virtusa Company. All Rights Reserved.