React Advanced Guide

Advanced React Study Guide

1. Advanced State Management

Redux & Redux Toolkit

  • Redux manages global state with actions and reducers.
  • Redux Toolkit simplifies Redux setup with createSlice and configureStore.

Sample Code (Redux Toolkit)

import { configureStore, createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
    decrement: (state) => state - 1,
  },
});

export const { increment, decrement } = counterSlice.actions;
export default configureStore({ reducer: { counter: counterSlice.reducer } });

Context API

  • Provides global state without additional libraries.

Sample Code

const ThemeContext = React.createContext('light');

const App = () => {
  return (
    <ThemeContext.Provider value="dark">
      <ChildComponent />
    </ThemeContext.Provider>
  );
};

Recoil or Zustand

  • Lightweight alternatives to Redux for state management.

Zustand Sample

import create from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}));

2. React Performance Optimization

Memoization

  • Use React.memo, useMemo, and useCallback to avoid unnecessary re-renders.

Sample Code

const MemoizedComponent = React.memo(({ value }) => {
  console.log('Rendered');
  return <div>{value}</div>;
});

Code Splitting

  • Load components lazily with React’s lazy() and Suspense.
const LazyComponent = React.lazy(() => import('./LazyComponent'));

React Profiler

  • Analyze performance bottlenecks.
import { Profiler } from 'react';

const onRenderCallback = (id, phase, actualDuration) => {
  console.log(`${id} took ${actualDuration}ms to render`);
};

<Profiler id="MyComponent" onRender={onRenderCallback}>
  <MyComponent />
</Profiler>;

3. Component Design Patterns

Higher-Order Components (HOCs)

  • Wrap components to enhance functionality.
const withLogger = (Component) => (props) => {
  console.log('Rendering');
  return <Component {...props} />;
};

const WrappedComponent = withLogger(MyComponent);

Render Props

  • Pass render logic as a function prop.
const DataProvider = ({ render }) => {
  const data = 'Hello';
  return render(data);
};

<DataProvider render={(data) => <h1>{data}</h1>} />;

Custom Hooks

  • Encapsulate logic in reusable hooks.
const useCounter = () => {
  const [count, setCount] = useState(0);
  return { count, increment: () => setCount(count + 1) };
};

4. Server-Side Rendering (SSR)

Next.js Example

export async function getServerSideProps() {
  const data = await fetchAPI();
  return { props: { data } };
}

5. TypeScript with React

  • Define types for props and state.
type ButtonProps = { label: string };
const Button: React.FC<ButtonProps> = ({ label }) => <button>{label}</button>;

6. Testing

React Testing Library

test('renders correctly', () => {
  render(<Component />);
  expect(screen.getByText('Hello')).toBeInTheDocument();
});

End-to-End Testing (Cypress)

describe('App', () => {
  it('loads', () => {
    cy.visit('/');
    cy.contains('Welcome');
  });
});

7. React Ecosystem and Tooling

  • Configure Webpack, Babel, ESLint, and Prettier for a clean development environment.

8. API Integration

GraphQL with Apollo

import { useQuery } from '@apollo/client';
const { data } = useQuery(GET_USERS);

9. Authentication and Authorization

OAuth & JWT Example

const token = localStorage.getItem('token');
const headers = { Authorization: `Bearer ${token}` };

10. Code Architecture

Monorepos with Nx

npx create-nx-workspace myorg

11. Web Performance Optimization

  • Use lazy loading and service workers.
navigator.serviceWorker.register('/sw.js');

12. Accessibility (a11y)

  • Use ARIA attributes and keyboard navigation.
<button aria-label="Close">X</button>

13. Security Best Practices

  • Prevent XSS and CSRF attacks.
const safeHTML = DOMPurify.sanitize(userInput);

14. AI & Machine Learning in React

  • Use TensorFlow.js for AI-powered features.
import * as tf from '@tensorflow/tfjs';

This guide provides an overview of advanced React concepts with sample implementations.

Post Comment