-
Notifications
You must be signed in to change notification settings - Fork 2
Coding guidelines
- Directories/Folders: snakecase
- Component: PascalCase
- Types: PascalCase
- Function: camelCase
- Variables: camelCase
- Event handlers: camelCase (prefix with handle, example handleClick)
- Constants: Constant case (Allcaps with underscore)
- Custom hooks: camelCase (prefix with use example useCount)
Always prefer .catch() for handling errors to maintain clean, readable, and idiomatic TypeScript code.
Example
// Preferred
fetchData()
.then(processData)
.then(logResult)
.catch((error) => {
console.error("An error occurred:", error);
});
// Discouraged
try {
fetchData().then(processData).then(logResult);
} catch (error) {
console.error("An error occurred:", error);
}Using .catch() aligns with the Promise API, avoids unnecessary nesting, and ensures consistent error handling. Save try...catch for async/await or synchronous code.
State Management in the Lowest Possible Component In React, it’s best practice to keep state local to the component that requires it, minimizing re-renders and increasing modularity.
Poor Practice: Managing state at a high-level parent component, causing excessive re-renders of child components. Good Practice: Keep state in the lowest component where it is needed. Lift state only when necessary or use tools like React Context API.
// Poor state management: Global state at a high level causing re-renders
const App = () => {
const [count, setCount] = useState(0); // Unnecessary global state could be in Child1
return (
<View>
<Child1 count={count} setCount={setCount} />
</View>
);
};
// Better state management: Keeping state local to components that need it
const Child1 = () => {
const [count, setCount] = useState(0);
return (
<View>
<Text>{count}</Text>
<Button title="Increment" onPress={() => setCount(count + 1)} />
</View>
);
};In React, components should be small, reusable, and handle a specific responsibility (Single Responsibility Principle). This modular approach makes the UI easier to manage.
// Breaking down a large component into smaller, reusable components
const App = () => (
<View>
<Header />
<TodoList />
<Footer />
</View>
);For shared logic across multiple components, use custom hooks to eliminate repetition and improve modularity.
// Custom hook for fetching data
const useFetchData = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(url);
const result = await response.json();
setData(result);
};
fetchData();
}, [url]);
return data;
};
// Usage in a component
const MyComponent = () => {
const data = useFetchData('/api/items');
return (
<View>
<Text>{JSON.stringify(data)}</Text>
</View>
);
};In this example, both the list of items and the item count are stored in state, even though the count can be derived from the array's length.
import { useState } from 'react';
const ItemList = () => {
const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);
const [itemCount, setItemCount] = useState(items.length); // Redundant state
const addItem = () => {
const newItems = [...items, `Item ${items.length + 1}`];
setItems(newItems);
setItemCount(newItems.length); // Manually updating redundant state
};
return (
<view>
<Text>Total Items: {items.length}</Text>
<FlatList
data={items}
renderItem={({ item }) => <Text>{item}</Text>}
keyExtractor={(item, index) => index.toString()}
/>
<Button title="Add Item" onPress={addItem} />
</View>
);
};
export default ItemList;ESLint is a widely-used linting tool that helps identify and fix problems in JavaScript. It can automatically enforce coding conventions, catch potential bugs, and improve the overall code quality. Using ESLint in a React project ensures consistent syntax, structure, and best practices across the team.
If you use Visual Studio Code, the ESlint extension can provide inline suggestions. If you use a IDE like WebStorm this should work out of the box. However, it might be necessary to run the command npm run lint to activate it.
If any of the enforced rules seem inappropriate or insufficient, please bring it up for discussion (or a pull request maybe), changes can be made in the .eslintrc.js file.
Everyone should utilise the Prettier plugin and the Prettier config from master to ensure consistency throughout the codebase. It helps avoid debates over style choices and commits changing it back and forth by automatically formatting the code according to predefined rules.
If any of the enforced rules seem inappropriate or insufficient, please bring it up for discussion (or a pull request maybe), changes can be made in the .prettier.config.json file.
Each file should include documentation explaining its purpose and how it interacts with other components. Complex code segments should be accompanied by comments clarifying the logic to ensure easier understanding.
Finally all the code should comply with React's own coding guidelines.