-
Prefer simple functions to declare components
-
Export not as default at the end of the file
-
Keep all your states declared first in your component function
-
useEffect
's should be declared first, before other internal methods -
Prefer
interfaces
overtypes
-
Destructure props
interface IProps { color: string; maxWidth?: number; } function MyComponent({color, maxWidth? = 100}: IProps) { const [myState, setMyState] = useState(0); useEffect(() => {}, []); const handleSomething = () => {} return (); } export { MyComponent }
- Folder structure
📁__tests__ |-📁components |-📁contexts |-📁hooks 📁src |-📁components |-📁MyAwesomeComponent |-📄index.tsx |-📄styles.tsx |-📁containers |-📁IncredibleContainer |-📄index.tsx |-📄styles.tsx |-📁ComplexContainer |-📁ComplexPieceContainer |-📄index.tsx |-📄styles.tsx |-📁ComplexPartContainer |-📄index.tsx |-📄index.tsx |- 📁contexts |-📃auth.tsx |-📃otherContext.tsx |- 📁hooks |-📃format.ts |- 📁pages |-📃Home.tsx |-📃UserProfile.tsx |- 📁services |-📁api |-📃apiClient.ts |-📃queryClient.ts |-📃routes.ts |- 📁store |-📃index.ts |-📃userSlice.ts |- 📁styles |-📃global.css |-📃theme.tsx
- Keep component and its styles under a folder named as the component name
- Keep test files outside of the
src
folder, and also keep them out of your final build - If needed, split your containers in smaller ones, keeping one index file that put it together.
- Use Atomic Design 🔗 to organize and decide about pages, containers, components and more.
-
Order your imports by importance (react always first, then other external libs, then your app items...)
-
Keep subjects close, as giving space between groups
import { useEffect, useState } from 'react'; import { Box } from 'material-ui'; import { useNavigate } from 'react-router-dom'; import { MyComponent } from '../components/MyComponent'; import { MyOtherCmp } from '../components/MyOtherCmp'; import { useAwesome } from '../hooks/awesome'; import { useGreeting } from '../hooks/greeting'; import { MyContextProvider, useMyContext } from '../contexts/myContext'; import { Container, Shadow } from './styles';
const MyContext = createContext<MyContextData>({} as MyContextData);
export const MyContextProvider = ({children}: IProps) => {
const fetchData = () => {...}
const contextValue = useMemo(() => ({
data,
fetchData
}), [data]);
return <MyContext.Provider value={contextValue}>{children}</MyContext.Provider>
}
export const useMyContext = () => {
const context = useContext(MyContext);
if(!context) throw new Error('useMyContext must be used within a MyContextProvider');
return context;
}
//MyContainer.tsx
export const MyContainer () => {
...
return (
<MyContextProvider>
<MyComponent />
<AnotherComponent />
</MyContextProvider>
)
}
//MyComponent.tsx
export cont MyComponent () => {
const [data, fetchData] = useMyContext();
...
return (
<div>{data}</div>
)
}