About React code structure

github logo ・1 min read

Hello,
I started learn Next JS. But there's one thing I don't understand.
There are many types of writing in React. I don't know which one is better to use.

For example;


function Test() { return

test }

export default () =>

test

class Prices extends React.Component {
// some code
}

export default Prices;


twitter logo DISCUSS (4)
markdown guide
 

For Function Components (FC) I prefer named functions

const Test () => {}
// or 
function Test() {}

export default Test

to export default () => {} syntax because of readability.

When you move your components around, say rename the file from Test.jsx to index.jsx for some reason, you have to dig thru code to see what it is for others.

You can use Class Components (CC) for handling error boundaries or to use life cycle methods not provided by Hooks (componentDidCatch & getDerivedStateFromError). CC isn't going away
but my personal opinion is that, FC with hooks seems to be where it's going (and I found FC w/ hooks much easier to write/reason about with shorter code).

 
 

It all depends on the component.

  1. Use class if you need to use component lifecycle methods.
  2. Other two are functional component with a bit different code style.
 

Mmm.. I'm understand.. whichever is easier and convenient then choose one

Classic DEV Post from Aug 23

Favorite Front-end/UI developer interview questions?

Help me compile your favorite interview questions.

Gündoğdu Yakıcı profile image
I am interested in Next.js and React native. I am also developing web systems on laravel.
Join dev.to

The fastest growing software community.
Free forever.