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.
@Letagoeve
Copy link

-Lindokuhle
-Letago

1.React.useContext is a hook provided by React that allows you to consume values from a context without explicitly passing props through the component tree
while Traditional prop drilling refers to the process of passing props down through multiple levels of nested components in order to deliver data from a parent component to a deeply nested child component that needs it

2.React.useContext is particularly useful in scenarios where you need to access global data or manage state that is relevant to multiple components across your application. Some common use cases for React.useContext include:
-Theme switching
-User authentication
-language localization
-Application configuration
-Data fetching and catching

3.In a React application, you can create and consume a context to share data or state across multiple components. First, you create a context using React.createContext(), typically in a separate file. Then, you wrap your components with a Provider component, passing the data or state you want to share as a value prop. In child components that need access to this context, you use the useContext hook to consume the context value. This allows you to dynamically render content or behavior based on the context value. Contexts are useful for providing global data or settings that need to be accessed by multiple components without prop drilling.

Example:
import React, { createContext } from 'react';

const UserContext = createContext({
name: '',
loggedIn: false,
});

export default UserContext;

4.While React.useContext offers simplicity for state management in React, it can become unwieldy and suffer from performance issues in larger applications. It lacks advanced debugging tools and middleware support, limiting its suitability for complex state logic. Compared to Redux or Zustand, which provide predictable state management, enhanced developer tools, middleware capabilities, and performance optimizations, useContext is better suited for simpler use cases within smaller applications.

5.Combining React.useContext with other state management libraries can be beneficial in situations where you need to manage both local component state and global application state simultaneously

Example:
Imagine an e-commerce application. You can use Redux to manage the user's authentication state (logged in user, shopping cart), order history, etc., which are relevant throughout the app.
Within a product listing component, you might use useContext to manage a local state variable for sorting or filtering products displayed on that specific page. This state doesn't need to be globally accessible, and keeping it separate from the global state managed by Redux helps prevent unnecessary updates and complexity.

@sthabiso-iv
Copy link

With @thewesss

  1. React.useContext is a hook that allows components to access data provided by a context. This differs from traditional prop drilling where data needs to be manually passed down through props at every level of the component hierarchy. useContext avoids this redundancy, making your code cleaner and easier to maintain, especially when sharing data across many nested components.
  2. Common use cases for React.useContext include managing global application state, theming, authentication status, and language preferences. It's preferred over Redux or MobX when dealing with simpler state management needs within a smaller application, reducing the complexity of setup and overhead associated with those libraries. Additionally, useContext is beneficial for components that need to access shared data without the need for prop drilling, leading to cleaner and more maintainable code.
  3. import { useContext } from 'react';
    import ThemeContext from './ThemeContext';

function Navbar() {
const { theme, toggleTheme } = useContext(ThemeContext);

return (
<nav style={{ backgroundColor: themes[theme] }}> {/* Use theme from context */}
Toggle Theme

);
}

  • We created a ThemeContext that holds the theme information (light by default).
  • The App component manages the theme state and provides the context with the current theme and a toggle function.
  • Both Navbar and potentially other components can access the theme and toggle functions using useContext.
  1. useContext is better for sharing simple app-wide data or managing isolated state in smaller applications. However, for complex state management or centralized control, Zustand or Redux can be considered.
  2. Combining React.useContext with other state management libraries can be beneficial when you have a mix of global and local state needs in your application. For instance, you might use a library like Redux or Zustand for managing complex global state, while using useContext for more localized state within specific components or features.
    One scenario where this could be beneficial is in a large e-commerce application where you have global state for managing user authentication, cart items, and product data using Redux. However, within individual product detail pages, you might use useContext to manage local state for features like displaying product variants, toggling product options, or tracking user interactions specific to that page. This hybrid approach allows for a flexible and efficient state management strategy tailored to different parts of your application.

@hunny-bee
Copy link

Bonolo, Sakhile, Ntandoyenkosi

  1. React.useContext is a hook in React that allows components to access and consume context values without the need to pass props through every level of the component tree, effectively bypassing "prop drilling." Traditional prop drilling involves passing data from a parent component to deeply nested child components through every intermediate component, which can become cumbersome and error-prone. In contrast, React.useContext enables a component to directly access the context value from the nearest matching Context. Provider in the component tree, simplifying state management and improving code readability.

  2. They are used to pass data deeply into the tree; to update data passed via context, to specify a default fallback value, and to override context for a part of the tree, amongst other things. We might want to use useContext for smaller applications or applications with a straightforward component structure; useContext also requires less setup compared to Redux or MobX

  3. In React, the Context API allows you to share state across multiple components without the need to manually pass props through each level of the component tree.

STEP 1; Creating the Context:

createContext() creates a new context object.
The MyProvider component uses the useState hook to create some state (value and setValue).
The MyProvider component returns a MyContext.Provider component that wraps children. The value prop of the provider is set to an object containing the state and the function to update it.

STEP 2; Using the Provider:

In App.js, the entire component tree (in this case, just MyComponent) is wrapped with MyProvider. This makes the context available to MyComponent and any other components that are descendants of MyProvider.

STEP 3; Consuming the Context:

In MyComponent, the useContext(MyContext) hook is used to access the context value, which includes the state and the updater function.
The component renders the current value and includes a button that, when clicked, updates the context value.

  1. Using React.useContext for state management can be limited by performance issues when many components consume the same context, leading to unnecessary re-renders. It also lacks built-in tools for complex state logic, debugging, and side effects management. Compared to tools like Redux or Zustand, which offer more efficient state updates, middleware support, and better developer tools, useContext is simpler but less scalable for large applications with intricate state requirements.

  2. Combining React.useContext with other state management libraries like Redux or Zustand can be beneficial for managing global state alongside localized state. For example, use Redux for global app state (e.g., user authentication status) while using useContext for state shared by a smaller component subtree (e.g., theme settings within a settings page). This approach optimizes performance and keeps state management more organized by using each tool for its strengths.

@NokulungaM
Copy link

Nokulunga
Phumlani
Samuel

  1. 'React.useContext' is a hook provided by the React library that allows you to consume a context value within a functional component. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
    React.useContext differs significantly from traditional prop drilling in how it provides and accesses data within a component tree.

  2. React.useContext is particularly useful in scenarios where you need to share data or functionality across multiple components without resorting to prop drilling.
    Choosing React.useContext over more complex state management solutions like Redux or MobX depends on the specific needs of your application. For example for smaller projects you use less complete state management. Useful for sharing data between components.

  3. a) Create a Context - First, create a new context using React.createContext. This will create a context object with Provider and Consumer properties.

Example:
// MyContext.js
import React from 'react';

const MyContext = React.createContext();

export default MyContext;

b) Provide the Context - Next, create a provider component that uses the Provider component of the context to pass down the data to the component tree.

Example:
// MyProvider.js
import React, { useState } from 'react';
import MyContext from './MyContext';

const MyProvider = ({ children }) => {
const [value, setValue] = useState('Hello, World!');

return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
);
};

export default MyProvider;

c) Consume the Context - Use the useContext hook within a functional component to access the context value.

Example:
// MyComponent.js
import React, { useContext } from 'react';
import MyContext from './MyContext';

const MyComponent = () => {
const { value, setValue } = useContext(MyContext);

return (


{value}


<button onClick={() => setValue('Hello, React!')}>Change Value

);
};

export default MyComponent;

4.1. A) Performance Issues with Frequent Update

React.useContext:
Limitation: Re-renders all consuming components whenever the context value changes, which can lead to performance issues.
Mitigation: Use memoization or split the context into smaller contexts.

Redux:
Advantage: Uses a single global state tree and connects components via connect or useSelector, allowing for more selective updates.
Mitigation: Redux's mapStateToProps or useSelector with shallow equality check can minimize re-renders. Additionally, Redux Toolkit provides built-in memoization for selectors.

Zustand:
Advantage: Minimal re-renders due to the way Zustand manages state. Components only re-render if the part of the state they use changes.
Mitigation: Zustand's useStore hook can select specific parts of the state, leading to more efficient updates.

B). Granularity of State Updates

React.useContext:
Limitation: No built-in mechanism for fine-grained updates; entire context value changes trigger re-renders.
Mitigation: Split context or use custom hooks for finer control.
Redux:

Advantage: Granular control over state updates through reducers and selectors.
Mitigation: Use of combineReducers and custom selectors to manage and access specific parts of the state.

Zustand:
Advantage: Direct access to specific parts of the state without triggering global re-renders.
Mitigation: Zustand's selector functions provide fine-grained control over state selection and updates.

C) No Middleware Support

React.useContext:
Limitation: Lacks middleware support for handling side effects.
Mitigation: Combine with custom hooks to handle side effects, though this can get complex.

Redux:
Advantage: Extensive middleware ecosystem (e.g., Redux Thunk, Redux Saga) for handling asynchronous actions, side effects, and complex state transitions.
Mitigation: Middleware can be added and configured easily to handle various side effects.

Zustand:
Advantage: Supports middleware for state persistence, logging, and more.
Mitigation: Zustand's middleware functions can be used to extend functionality (e.g., zustand/middleware).

D) Scalability and Maintainability

React.useContext:
Limitation: Can become cumbersome with multiple contexts in large applications.
Mitigation: Use well-structured context management and custom hooks, but may still face scalability issues.

Redux:
Advantage: Designed for large-scale applications with complex state requirements. Provides clear structure and separation of concerns.
Mitigation: Use Redux Toolkit for more maintainable and scalable code with less boilerplate.

Zustand:
Advantage: Simple and minimalistic API that scales well with application size.
Mitigation: Zustand's modular approach allows for easy scaling without introducing significant complexity.

E) Debugging and Tooling

React.useContext:
Limitation: Limited debugging and tooling support compared to more mature state management libraries.
Mitigation: Use React DevTools, but lacks advanced features like time-travel debugging.

  1. it can be beneficial in situations where you need to manage different scopes or granularities of state within your application.
    Example:
    Example Scenario: E-commerce Application
    Imagine you are developing a large e-commerce application with multiple components that need to access and update the user's shopping cart, user authentication state, and product details. Here's how combining useContext with a state management library like Redux can be beneficial:

@MissAngelaKing
Copy link

MissAngelaKing commented Jun 11, 2024

Emihle Matyolo
Sharon Matjila
Angela King

  1. React.useContext is a hook that allows you to access context (shared state) in a functional component. It differs from traditional prop drilling because with traditional prop drilling, props need to pass through several layers of nested components to reach the deeply nested child component which needs the prop , whereas, React.useContext passes data through the component tree without having to pass props manually at every level.

  2. React.useContext is a hook for accessing context values directly in components, avoiding prop drilling. It's ideal for theming, localization, authentication, and simple global state management in small to medium apps. It’s simpler and more lightweight than Redux or MobX for straightforward state needs and it also avoids unnecessary re-renders. Redux: more complex, better for large-scale apps and MobX: more reactive, better for complex, dynamic data.

  3. Creating and consuming a Context:

  4. Create a Context using React.createContext()

  5. Create a Provider component that wraps your app and provides the context

  6. Use the useContext hook in a component to access the context

Basic example:

// Create a context
const ThemeContext = React.createContext();

// Create a provider
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};

// Consume the context
const Button = () => {
const { theme } = useContext(ThemeContext);
return Click me!;
};

// Wrap the app with the provider


  1. Limitations of React.useContext:
  • Not suitable for complex, global state management
  • Can lead to tight coupling between components
  • No built-in debugging tools

Compared to Redux or Zustand:

  • Redux: more robust, better for large-scale apps
  • Zustand: more scalable, better for complex apps
  • useContext: simpler, better for small-scale apps
  1. Use useContext for managing simple UI-related state like theming or language selection, while using Redux or Zustand for managing more complex application state such as data fetching, caching, and synchronization. You want to use a library like Redux for complex state management, but also want a simple way to share small pieces of state between components.

Example scenario:

  • Use Redux for user authentication and app-wide data
  • Use React.useContext for theming or language settings
    This way, you can leverage the strengths of each library to manage different aspects of your application's state.

@ndlovusimphiwe68
Copy link

Simphiwe Ndlovu
Mpilo Mthiyane
Koketso Lepulana

  1. React.useContext is a hook in React, a popular JS library used for building interfaces. By using .useContext components can access shared state or data without having to pass props down manually through intermediate components. its hook that is used to pass/ share states on deeply nested component

  2. It includes sharing themes, managing authenticated user data. useContext might be preferred over Redux or MobX for simpler state management needs, reducing boilerplate code.

  3. Step #1 - Create a Contextimport {
    Step #2 - Wrap your App with Context Providerimport React from 'react';
    import MyContext from './MyContext';

const App = () => {
const sharedValue = 'This is a shared value';

return (
<MyContext.Provider value={sharedValue}>
{/* Your components go here */}
</MyContext.Provider>
);
};

export default App;
Step #3 - Consume the Context in Componentsimport React, { useContext } from 'react';
import MyContext from './MyContext';

const MyComponent = () => {
const sharedValue = useContext(MyContext);

return

{sharedValue}

;
};

export default MyComponent;

  1. Using React.useContext for state management has several limitations that can affect the scalability and performance of your application such as Frequent Re-renders, Single Context Per Use, Limited Debugging Tools and No Middleware Support:React.useContext is suitable for simple, less frequent state changes and avoiding prop drilling in small to medium-sized applications. It is limited by performance issues, lack of debugging tools, and complexity in managing multiple contexts.
    Redux offers robust performance optimization, scalability, advanced debugging tools, and middleware support, making it ideal for large applications with complex state management needs.
    Zustand provides a simpler and more flexible API with better performance optimizations compared to React.useContext, making it a good alternative for both small and larger applications that need a balance between simplicity and performance

  2. Separation of Concerns:

Use React.useContext for lightweight, application-wide settings that do not change frequently and do not require complex state management. Optimizing Performance:

Use React.useContext for state that is infrequently updated to avoid unnecessary re-renders.Improving Code Organization:

Use React.useContext to manage global configuration or contextual data that needs to be accessed by many components.

Example Scenario: E-commerce Application.

Theme Settings:

Dark mode or light mode, font size, and other UI preferences that affect the entire application but do not change frequently. User Authentication:

Current user information, authentication tokens, and user session management. Shopping Cart and Product Data:

Product listings, shopping cart items, and checkout processes that change frequently and require complex logic.

@Vuyo-Ngwane
Copy link

Vuyo
Konanani
Ntokozo

1.) React.useContext is a hook that allows you to access and consume context values in your functional components. Ease of Access:
Prop Drilling: Requires passing props through every level of the component tree, which can be cumbersome and error-prone.
useContext: Allows direct access to the context value without passing props through intermediate components.

2.) Can be used to pass down a theme to various components without using props. Manages user authentication state and provides user information to various components.

3.) // MyContext.js
import React, { createContext } from 'react';

// Create a context
const MyContext = createContext();

export default MyContext;

import React, { useContext } from 'react';
import MyContext from './MyContext'; // Import the context

function ChildComponent() {
const value = useContext(MyContext);

return

{value}
;
}

export default ChildComponent;

4.) Some of the limitations include React.useContext not having middleware, thus some of the functions have to be performed manually. useContext is limited to sharing state between components that are siblings or ancestors in the component tree. It does not provide a centralized store for managing global state across the entire application.

5.) When working on large scale applications it becomes more effective, e.g. combined tools such as Redux van be utilised for managing the global application state. It can also be used to manage the local UI State. Examples include an e-commerce application global State (Manage user authentication, cart items, and other global states that need to be accessed and updated across the entire application).We can use LocalStorage to Manage theme settings (e.g., light/dark mode) that are only relevant to specific parts of the application, such as a settings page or a specific component tree.

@thabiso-makolana
Copy link

Thabiso
Siyabonga

  1. is a hook in React that allows components to subscribe to context changes. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
  2. Common Use Cases for React.useContext
  • Theme Management: Switching between light and dark themes across the application.
  • Localization: Providing localization data and functions to translate strings

When to Use React.useContext Over Redux or MobX:

  • Simplicity: For small to medium-sized applications where the complexity of Redux or MobX is unnecessary.
  • Component-Specific State: When the state is only relevant to a specific part of the component tree.
  • Avoiding Boilerplate: When you want to avoid the boilerplate code associated with Redux or MobX.
  1. Create a Context:
    `import React, { createContext, useContext, useState } from 'react';

const MyContext = createContext();

const MyProvider = ({ children }) => {
const [value, setValue] = useState('Hello World');
return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
);
};
`

Consume the Context:
`const MyComponent = () => {
const { value, setValue } = useContext(MyContext);

return (


{value}


<button onClick={() => setValue('Hello React')}>Change Value

);
};

// Using the provider and component in an application
const App = () => (



);

export default App;
`
4. Limitations of React.useContext:

  • Performance: Re-rendering all consumers when the context value changes can lead to performance issues.
  • Debugging: Limited debugging tools compared to Redux, which has extensive middleware and developer tools.

Comparison with Redux and Zustand:

  • Redux: Provides more control over state changes and is better suited for large-scale applications with complex state interactions. Redux's middleware ecosystem and dev tools make it more powerful for debugging and managing side effects.
  • Zustand: More lightweight than Redux, but offers more performance and control compared to useContext. It provides fine-grained reactivity, meaning only components that depend on a piece of state will re-render when that state changes.
  1. Scenario:
    Imagine you have a large e-commerce application. You use Redux to manage the global state, such as the shopping cart, user authentication, and product listings, because it provides robust state management and debugging tools. However, you have a feature for toggling the UI theme (light/dark mode) that doesn't need to interact with the global state and is better suited for context.

@PamelaGwala
Copy link

@Tumelo2748
@katleho Mafalela

1)is a hook in React that allows you to access the context API more conveniently. It enables you to share state and other values across a component tree without having to pass props down manually at every level, a process known as "prop drilling."
2)UseContext can used in a situation like an app that has different themes like dark mode and light mode so in this case a useContext will be useful. We prefer React.useContext over Redux or MobX when it comes to simplicity and minimalism, performance consideration and smaller applications.
3)
import React, { createContext, useState, useContext } from 'react';
import ReactDOM from 'react-dom';

// 1. Create a Context
const ThemeContext = createContext();

// 2. Create a Provider Component
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));

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

// 3. Consume the Context in a Component
const ThemedComponent = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff', padding: '20px' }}>

Current theme: {theme}


Toggle Theme

);
};

// Wrap your application with the Provider
const App = () => (



);

ReactDOM.render(, document.getElementById('root'));

  • first we creating the Context: ThemeContext is created using createContext().
  • Provider Component: ThemeProvider manages the theme state and provides it to its children via the ThemeContext.Provider.
  • Consuming the Context: ThemedComponent uses useContext(ThemeContext) to access the theme and a function to toggle it.
    Wrapping the Application: The App component wraps its children with ThemeProvider to provide theme context to the entire application.

4)React.useContext is a convenient way to manage state within a React application, but it comes with limitations compared to specialized state management libraries like Redux or Zustand. While it simplifies state management and reduces boilerplate, it may lead to performance issues, especially in large applications with frequent state updates. Additionally, managing complex state and debugging can be more challenging with React.useContext compared to Redux, which offers a structured approach and advanced tooling. Zustand provides a middle ground with simpler API and better performance optimizations, making it suitable for applications that require more advanced state management than React.useContext but do not need the full complexity of Redux. Ultimately, the choice between these tools depends on the specific needs and complexity of your application.

5)Combining React.useContext with Redux or other state management libraries allows for a flexible approach to managing different aspects of state in a React application. By leveraging the lightweight simplicity of React.useContext for localized state needs, such as theme preferences, alongside the robustness of Redux for complex state management tasks like user authentication, developers can achieve a well-structured and efficient state management solution tailored to the specific requirements of their application.

@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