🌍Routing, Context, and State Management

Learn how to manage application state and navigation in React apps.

πŸ—ΊοΈ React Router Deep Dive

πŸŽ›οΈ Global State with Context API

Global state refers to data that needs to be accessed across multiple components in your React application. Unlike local component state, global state is not tied to a single component and can include things like themes, authentication status, or application-wide configurations.

πŸ’‘ When to Use Global State?

  • When data needs to be accessed by multiple components at different levels of your component tree.
  • For application-wide settings like dark/light themes or language preferences.
  • To manage complex state that would otherwise require extensive prop drilling.

πŸ’‘ Introducing React's Context API

React's Context API provides a way to share global state throughout your application without passing props through every level of the component tree. It is particularly useful for data that needs to be accessed by many components but doesn't change frequently.

βœ… Using `useContext` and Context Providers

// Create a theme context
const ThemeContext = React.createContext({
  isDark: false,
  toggleTheme: () => {},
});

// Provider component
function ThemeProvider({ children }) {
  const [isDark, setIsDark] = useState(false);

  const toggleTheme = () => {
    setIsDark(!isDark);
  };

  return (
    <ThemeContext.Provider value={{ isDark, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// Consumer component
function ThemedButton() {
  const { isDark, toggleTheme } = useContext(ThemeContext);

  return (
    <button
      onClick={toggleTheme}
      style={{ backgroundColor: isDark ? 'black' : 'white' }}
    >
      Toggle Theme
    </button>
  );

πŸ’‘ Best Practices for Using Context API

  • Use context only when necessary - overusing it can lead to performance issues.
  • Avoid storing large amounts of frequently changing state in context.
  • Memoize components that consume context to prevent unnecessary re-renders.

πŸ’‘ Performance Considerations

When using the Context API, it's important to remember that changes to context values will cause all consuming components to re-render. To prevent unnecessary re-renders, consider using React.memo or useMemo for components that consume context.

❌ Common Mistakes to Avoid

  • Avoid creating multiple contexts for the same type of data.
  • Don't use context for local component state that doesn't need to be shared.
  • Avoid deep nesting of providers without a clear reason.

βš–οΈ Redux and Alternatives

Global state management is a critical concept in React applications, allowing you to maintain and update data across multiple components. In this chapter, we'll explore Redux and its modern alternative Redux Toolkit, while also introducing simpler solutions like Zustand, Recoil, and Jotai.

πŸ’‘ Why Global State Management?

  • Avoiding prop drilling by centralizing state
  • Maintaining a single source of truth for application data
  • Facilitating complex state updates across components
  • Supporting asynchronous operations and side effects

βœ… Redux Toolkit Basics

Redux Toolkit simplifies state management with a modern approach:

  • Install Redux: npm install @reduxjs/toolkit react-redux
  • Create store configuration
  • Define slices for different parts of your state
  • Implement actions and reducers
import { configureStore } from '@reduxjs/toolkit';

const store = configureStore({
  reducer: {
    counter: counterSlice.reducer,
    user: userSlice.reducer
  }
});

πŸ’‘ Advanced Redux Concepts

  • Thunks for asynchronous operations
  • State persistence with localStorage
  • Optimizing performance with reselect
  • Handling multiple reducers and slices
export const incrementAsync = (amount = 1) => {
  return async (dispatch) => {
    dispatch(incrementByAmount(amount));
  };
};

❌ Alternatives to Redux

While Redux is powerful, it might be overkill for simpler applications. Consider these alternatives:

  • Zustand: Minimal and easy-to-learn state management library
  • Recoil: React-specific state management with support for atoms and selectors
  • Jotai: Simple and lightweight alternative focused onAtoms
const count = useAtom(counterAtom);

function Component() {
  const [count, setCount] = useAtom(counterAtom);
  return <div>{count}</div>;
}

πŸ’‘ When to Use Each Solution

  • Use Redux for large-scale applications with complex state logic
  • Choose Zustand or Jotai for simpler projects needing lightweight state management
  • Consider Recoil when building highly interactive UIs with dependency-based updates

Quiz

Question 1 of 9

Which scenario is most appropriate for using React's Context API?

  • Storing local component state that doesn't need to be shared.
  • Managing application-wide settings like theme preferences.
  • Passing props between sibling components.
  • Storing temporary state for a single form submission.