Skip to content

Instantly share code, notes, and snippets.

@halitbatur
Created June 10, 2024 06:57
Show Gist options
  • Save halitbatur/57a1724f564a8ce2ca92873f6261e87c to your computer and use it in GitHub Desktop.
Save halitbatur/57a1724f564a8ce2ca92873f6261e87c to your computer and use it in GitHub Desktop.
Context API and state management discussion
  1. What is React.useContext, and how does it differ from traditional prop drilling?
  2. What are some common use cases for React.useContext, and when might you prefer to use it over other state management solutions like Redux or MobX?
  3. How do you create and consume a Context in a React application? Can you walk through a basic example?
  4. What are the limitations of using React.useContext for state management? How do these limitations compare to other tools like Redux or Zustand?
  5. In what situations might it be beneficial to combine React.useContext with other state management libraries? Provide an example scenario.
@Gracepinkie
Copy link

@Geraldmutsw
@Gracepinkie(sinethemba),
Lethukuthula

1.useContext is a react hook that allows functional components to access data from a react context without explicitly passing props through every level of the component tree. this helps avoid prop drilling, which can become cumbersome and error-prone in deeply nested component hierarchies.

  1. Use Cases for React.useContext : useContext is ideal for sharing data across multiple components without the need for prop drilling and When you only need to access a specific context value within a subtree, useContext is concise and efficient.
    .When to Prefer useContext Over Redux or MobX: If your state management needs are small or local (e.g., a few components sharing a theme), useContext is lightweight and straightforward and useContext reduces boilerplate and makes your code cleaner.

3.to create a context you use React.createContext() to create a context object. first you import create context "import React, {createContext} from 'react'" then declare the variable that will hold the created context "const ThemeContext = createContext({theme: 'light'})" then after we export the function "export default ThemeContext".

.To consume the context you will firstly wrap for example my parent component with a provider component to enable the child components to have access to the context. first you call in the useContext hook and pass in the created context as the parameter/argument "const {them, setTheme} = useContext(ThemeContext)" then call whatever that is in the context like return(<div style{{backgroundColor: theme}})>

4.Context is useful for smaller state operations, such as passing data between sibling components. It's also great for reducing prop drilling and making your code cleaner. However, it should not be used for global state, modular-level state, or app state.

  1. Scenario :an e-commerce application built with Redux for managing product data, shopping cart, and user authentication. You might use useContext to manage a separate state for UI themes (light/dark mode) that needs to be accessed by various components throughout the app. This way, you leverage Redux for complex state like product inventory, while keeping theme management simpler with useContext.

@PhamelaMhlaba
Copy link

Team Members(Phamela and Mpho)
Answers.

1 . React.useContext is a hook that allows components to access context values directly, avoiding the need to pass props through multiple levels of the component tree.

Differences from Prop Drilling:

  • Simplifies Component Structure: No need to pass props through every level.
  • Direct Access: Components can access context values directly.
  • Reduces Coupling: Easier to manage and refactor.
  1. Common Use Cases for `React.useContext:
  • Theming: Managing light/dark mode or custom themes.
  • Localization: Handling language preferences.
  • User Authentication: Accessing user info and authentication state.
  • Global State: Sharing non-complex global data like UI state.

When to Prefer useContext Over Redux or MobX:

  • Simplicity: For small to medium-sized apps with less complex state.
  • Minimal Setup: Avoiding the boilerplate and configuration of Redux/MobX.
  • Performance: When the app doesn’t require advanced state management features like middleware or time-travel debugging.
  1. Create Context: React.createContext() sets up the context.
    const MyContext = React.createContext();

    Provide Context: Use <Context.Provider> to supply value.
    const MyProvider = ({ children }) => {
    const value = { /* shared state or value */ };
    return (
    <MyContext.Provider value={value}>
    {children}
    </MyContext.Provider>
    );
    };

    Consume Context: Use useContext(Context) to access value.
    const MyComponent = () => {
    const contextValue = useContext(MyContext);
    return (

    {/* use contextValue here */}

);
};

  1. Limitations of `React.useContext:
  • Re-renders: All consuming components re-render on value change.
  • Scalability: Harder to manage complex state logic.
  • Debugging: Fewer tools for tracking state changes.
  • Middleware: No built-in support for side effects.

Compared to Redux or Zustand:

  • Redux: Redux is great at handling complicated state, has useful tools for developers, but needs more initial setup.
  • Zustand: Zustand has an easy-to-use interface, makes your app faster when updating, requires less initial setup, and doesn't come with as many extra tools as Redux.

React.useContext is best for simple state needs; use Redux or Zustand for more complex state management.

  1. Combining React.useContext with state management libraries is useful for optimizing performance and separating concerns.

Example:

  • Redux: Handles global state like user authentication.
  • useContext: Manages local UI state like themes.

@NonhlanhlaMazibuko
Copy link

Nonhlanhla Mazibuko, Hophney Lentsoana and Nhlanhla Msibi

  1. useContext is a React hook that provides a way to access context values directly within a functional component.
    It eliminates the need for prop drilling, making your component hierarchy cleaner and easier to manage.

  2. Common use cases of useContext can be Theme management; we can create a ThemeContext to manage light and dark themes across the web page. We can also use useContext to manage and provide authentication across your application. useContext combined with other React hooks like useState can be more efficient when we are working on a small-scale applications or when managing applications that have non-complex states or state management is only required for a few components only).

  3. We create a context using React.createContext(). we use the UserContext.Provider to wrap the component tree that needs access to the user context and we then we use the useContext hook to access the context value.

  4. useContext provides a single context value to all consuming components. This means that any change in the context value will trigger a re-render in all consuming components, even if the component only needs a subset of the context data. This can lead to unnecessary re-renders and degraded performance, especially in large applications. In Redux, connect or useSelector can be used to map specific pieces of state to components, reducing unnecessary re-renders. Zustand uses a subscription-based approach where components only re-render when the specific parts of the state they depend on change.

  • It can be harder to trace and debug state updates since the context API abstracts away some of the explicit state management.
  • For managing global state, using useContext can become cumbersome as your application grows. You may need to create multiple contexts for different parts of the state, leading to increased complexity in managing and providing these contexts. Redux provides a more structured and predictable approach to state management with actions, reducers, and a centralized store. This structure is beneficial for large applications with complex state interactions. Zustand offers a more flexible and straightforward API for managing state with minimal boilerplate, which can be easier to use than Redux for moderate complexity.
  1. useContext is great for simple app-wide data. For complex state or multiple stores, consider Redux + useContext. Example: Redux manages product data, useContext holds user theme preference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment