The Anatomy Of My Ideal React Component
Tags: react, javascript, typescript
Published: 2022-03-11 18:52:02

---
title: The Anatomy Of My Ideal React Component
published: true
description: A walkthrough of my very opinionated React Component.
tags: react, javascript, typescript
cover_image: https://cdn.antjanus.com/images/react-banner.jpg
---

```ts
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import tw from 'twin.macro'

import { USER_ROUTES, useUser } from 'modules/auth'
import { Loader } from 'modules/ui'
import { usePost } from 'modules/posts'

import { EmptyFallback } from './emptyFallback'

const StyledContainer = styled.div`
  ${tw`w-100 m-auto`}
`

const StyledHeading = styled.h1`
  ${tw`text-lg`}
`

type PostProps = {
  id: string
}

export const Post = ({ id }: PostProps): JSX.Element => {
  const [isExpanded, setIsExpanded] = useState(false)

  const { isLoading, isSuccess, post } = usePost({ id })
  const { user } = useUser()

  if (isLoading) {
    return <Loader />
  }
  
  if (!isLoading && !post) {
    return <EmptyFallback />
  }

  return (
    <StyledContainer>
     <Link to={USER_ROUTES.ACCOUNT}>Back to account, {user.name}</Link>
     <StyledHeading>{post.title}</StyledHeading>
     {post.body}
    </StyledContainer>
  )
}
```

This is how I write my components and how I prefer to write React. It's a _super specific_ way that works for me - and that includes using [styled-components](https://styled-components.com/). If you have suggestions on how to improve this structure, I'm all ears. I love to improve how I do things and I greatly enjoy feedback.

I'll drop questions in the article if you'd like to give me feedback on those!

For anyone new to React or JS or development or TS, don't even worry about all that this is doing. I really just wanted to showcase a complicated example.

> **Note:** I wanted to stress this again -- this is what works for me. I'd love to hear about what works for you! 

## Imports

Does import order matter? Not really. But I like to have rules around them especially for bigger components that might have 20 lines of imports _or more_. And that happens more than I'd like to admit. My general heuristics are:

1. React up top no matter what
2. 3rd party library imports (followed by a new line)
3. internal library imports (and aliased imports)
4. local imports

```ts
// react
import React, { useEffect } from 'react'

// 3rd party libraries
import moment from 'moment'
import styled from 'styled-components'

// internal shared components/utils/libraries
import { ListItems, useItems } from 'modules/ui'

// local
import { EmptyFallback } from './EmptyFallback'
```

> **Why?** When you deal with more than a handful of imports, it's really easy to get lost in what the file is using. Having conventions around imports makes it easier for me to see what it's using at a glance

## Styled Components

No matter what library you use, you are writing your CSS _somewhere_. I'm a fan of styled-components (we use them at work) and [Tailwind](https://tailwindcss.com/) (I use it in personal projects). [Twin](https://github.com/ben-rogerson/twin.macro) allows you to combine them together -- that way you can write custom CSS if you need to, and Tailwind is great for rapid prototyping and production-ready apps alike. Best of both worlds.

I put these at the top because my components below typically use them. If there are too many styled components, I tend to put them in a co-located `styled.ts` file.

I also tend to prefix styled components with `Styled`. Something I learned at work. It quickly distinguishes between styling components and components that do more than that.

```ts
const StyledContainer = styled.div`
  ${tw`w-full`}

  background-color: ${COLORS.CONTAINER_BACKGROUND};
`

export const SomeComponent = () => {
  // logic
  const items = useItems()

  return (
   <StyledContainer> {/* styled component that does nothing else */}
    <List items={items} /> {/* component with internal logic */}
   </StyledContainer>
  )
}
```

> **Why?** I prefer co-located styling but also, put these up top so they're separate from components that have more than styling.

> **Questions for you:** How do you organize your styled components? If you have a file with styled components, what do you call it?

## Component Types

I typically name my Component types as `ComponentNameProps` and `ComponentNameReturn` where most of the time, I skip the "return" to use `JSX.Element` (I do use the `Return` type for hooks though! I'll write about that another day). Check out the [React TypeScript CheatSheet](https://react-typescript-cheatsheet.netlify.app/) which contains majority of the conventions I use for TypeScript and React.

This convention (naming and placement) makes it clear that:

1. this type belongs to the component
2. this type _isn't_ shareable
3. where to find the typing (right above the component)

It's also a stylistic choice not to inline it but you can:

```ts
// I don't like this
const SomeComponent = ({ 
  id,
  isEnabled,
  data,
  filter,
  onClick
}: {
  id: string,
  isEnabled: boolean
  data: DataStructureType
  filter: FilterType
  onClick: () => void
}): JSX.Element => {}

// I do like this
type SomeComponentProps = {
  id: string,
  isEnabled: boolean
  data: DataStructureType
  filter: FilterType
  onClick: () => void
}

const SomeComponent = ({ 
  id,
  isEnabled,
  data,
  filter,
  onClick
}: SomeComponentProps): JSX.Element => {}
```

I feel like I have to constantly re-emphasize: this is what works for me specifically. There's no science or research behind this. It's not "easier to reason about" (which most of the time means "I like this", anyways).

> **Why?** Co-located component types right above the component declaration make it easier _for me_ to see the Component's purpose and signature at a glance

> **Questions for you:** Do you co-locate your component types? Do you prefer inling them?

## Component structure

Ok, let's dig into the Component structure. I think components typically have the following parts to them (some more or less, depending on what you're doing):

1. local state (useState, useReducer, useRef, useMemo, etc.)
2. non-React hooks and async/state fetching stuff (react-query, apollo, custom hooks, etc.)
3. useEffect/useLayoutEffect
4. post-processing the setup
5. callbacks/handlers
6. branching path rendering (loading screen, empty screen, error screen)
7. default/success rendering

More or less, but let's go through them:

```ts
// local state
const [isExpanded, setIsExpanded] = useState(false)

// non-react hooks
const { isLoading, post } = usePost({ id })

// useEffect
useEffect(() => {
  setIsExpanded(false) // close expanded section when the post id changes
}, [id])

// post processing
const snippet = generateSnippet(post)

// callbacks and handlers
const toggleExpanded = (e: Event): void => {
  setIsExpanded((isExpanded) => !isExpanded)
}

// branching path rendering
if (isLoading) {
  return <Loading />
}

if (post && !isExpanded) {
  return (
    <StyledContainer>{snippet}</StyledContainer>
  )
}

// default/success render
return <StyledContainer>
  <h1>{post.title}</h1>
  <div>{post.content}</div>
</StyledContainer>
```

So a few things about this, I set this up so that the logic seems to flow down and we declare as much ahead of time as possible. I think there is quite a bit of wiggle space here because what really matters is declaring variables and using hooks before we render. This is _necessary_ for hooks to work right. If you try to short-circuit a render and skip a hook as a result, React will let you know that's an issue.

I also like to add the handler at the end of that declaration block so I have access to any variables I might need if I convert it to use `useCallback`. Which is also why I use `const func = () => {}` instead of `function func() {}` -- to quickly convert to useCallback and to avoid a mismatch of named functions and lambdas.

We can then safely jump into branching path rendering for loading screens, errors, etc. without worrying about hooks. We can exit the render safely early this way. 

And lastly, I keep the default/success render at the bottom. 

> **Why** It's a lot to cover but honestly, it's all personal preference influenced by React's requirement to always run all hooks in a component.

> **Question** Does this differ much from your standards?

## Potential For Refactor
You might notice that my original component doesn't have a useEffect or the post-processing examples. Why is that?

Typically, if I have to do some lifting in a component to get data in a specific state, or I have variables that relate to each other, I like to hide that in a hook.

For example:

```ts
type UsePostProps = {
  id: string
}

type UsePostReturn = {
  isExpanded: boolean
  post: PostType
  isLoading: boolean
  toggleExpanded: () => void
}

export const usePost = ({ id }: UsePostProps): UsePostReturn => {
  const [isExpanded, setIsExpanded] = useState(false)
  const { isLoading, data } = useQuery('cache', getPost)

  useEffect(() => {
    setIsExpanded(false)
  }, [id])

  const post = !isLoading && formatPost(data)

  return {
   isExpanded,
   toggleExpanded,
   isLoading,
   post,
  }
}
```

> **Why** I'm not sure. I don't like big components, I don't like components that do too much so I split logic up into hooks however feels right to me.

> **Question** How do you feel about wrapping API calls in custom hooks by default? eg. any unique call has its own hook that handles data transformation, related state, and the fetching. And do you prefer to have this logic inside of a component? 

## Wondering about folder structure?

I made a [React application structure video](https://www.youtube.com/watch?v=SvR0_lWkPmU) on that topic. Though, in hindsight, it has a few syntax errors I didn't notice while recording.