Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

Follow publication

Top 5 React Best Practices Every Developer Should Know

Danusha Navod
Bits and Pieces
Published in
9 min readMar 7, 2024

1. Composable Software Architecture

(https://www.netsolutions.com/insights/composable-architecture-why-its-important/)

Composability in React

2. State Management

1. useState

const Counter = () => {
const [count, setCount] = useState(0);

const handleClick = () => {
setCount(count + 1);
};

return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
};

2. useReducer

const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + 1 };
default:
return state;
}
};

const Counter = () => {
const [state, dispatch] = useReducer(reducer, { count: 0 });

const handleClick = () => {
dispatch({ type: 'increment' });
};

return (
<div>
<p>Count: {state.count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
};

3. Context API

// Creates the new context
const ThemeContext = React.createContext('light');

const App = () => {
const [theme, setTheme] = useState('light');

const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};

return (
<ThemeContext.Provider value={theme}>
<Toolbar toggleTheme={toggleTheme} />
<Content />
</ThemeContext.Provider>
);
};

const Toolbar = ({ toggleTheme }) => {
// Access the context
const theme = useContext(ThemeContext);

return (
<div>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};

const Content = () => {
// Access the context
const theme = useContext(ThemeContext);

return (
<div style={{ backgroundColor: theme }}>
{/* Content based on theme */}
</div>
);
};

3. Immutability

// Without TypeScript:
let user = { name: "John", age: 30 };
user.age = 31; // Can modify the object accidentally

// With TypeScript:
const user: Readonly<{ name: string; age: number }> = { name: "John", age: 30 };
// user.age = 31; // TypeScript will throw an error
const originalArray = [1, 2, 3];
const newArray = originalArray.concat([4]); // Modifies original array
const updatedArray = [...originalArray, 4]; // Creates a new array with spread

const originalObject = { name: "Jane" };
const updatedObject = { ...originalObject, age: 30 }; // Creates a new object with spread
const originalArray = [1, 2, 3];
const newArray = originalArray.concat([4]); // Returns a new array
const subArray = originalArray.slice(1, 3); // Returns a new sub-array

4. Lifecycle Methods and Hooks

useEffect

useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty array for one-time execution on mount

useState

const [data, setData] = useState(null);

useEffect(() => {
if (!data) {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}
}, [data]);

5. Optimization

1. Code Splitting

// App.js
import React, { Suspense } from 'react';

const Home = React.lazy(() => import('./components/Home'));
const About = React.lazy(() => import('./components/About'));

function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<Home />
</Suspense>
<Suspense fallback={<div>Loading...</div>}>
<About />
</Suspense>
</div>
);
}

2. Memoization

// ExpensiveComponent.js
import React, { useMemo } from 'react';

function ExpensiveComponent({ data }) {
const processedData = useMemo(() => {
// Perform expensive calculations on data
return processedResult;
}, [data]);

return (
<div>{processedData}</div>
);
}

Wrapping Up

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development