Mastering React Hooks: Unleashing the Power of useContext and useReducer React Hooks Part 2

Knowledge Base, React

Published: 31.01.2024

In the dynamic realm of React development, understanding and harnessing the potential of hooks is essential. In the second installment of our React Hooks series, we delve into the realms of useContext and useReducer. These hooks, when combined, offer a potent solution for managing state and context in a more efficient and organized manner.

Understanding useContext:

The useContext hook emerges as a game-changer, liberating developers from the burden of prop-drilling. While the standard React approach involves passing data from parent to child components, this can become cumbersome in deeply nested structures. Context, facilitated by useContext, provides a seamless way to transmit data across various parts of your application without the need for extensive prop passing.

To implement useContext, start by creating a new context object with React.createContext. This yields a Provider and a Consumer component, which can be deconstructed for use. The Provider component ensures that your state is accessible to every child component. Wrap your parent component with the Provider, providing a value prop with the desired accessible data. In child components, the Consumer component consumes this value for use.

However, useContext simplifies this process significantly. By passing the createContext object to useContext, you gain direct access to the values specified in the Provider. This eliminates the need for extensive nesting with Consumer components. Here's an example:


// VoetbalContext.js
const clubsEredivisie = {
    nummer1: "Ajax",
    nummer2: "PSV",
    nummer3: "Vitesse",
};
export const VoetbalContext = React.createContext(clubsEredivisie.nummer1);

// index.js
import React from 'react';
import { VoetbalContext } from "./VoetbalContext";
const App = () => {
    return (
        <VoetbalContext.Provider value={clubsEredivisie}>
             <Home />
         </VoetbalContext.Provider>
    );
}
export default App

// MyPersonalComponent.js
import React, { useContext } from "react";
import VoetbalContext from './VoetbalContext';
const MyPersonalComponent = () => {
    const clubs = useContext(VoetbalContext);
    return (
        <div>
            <div>De nummer 1 club van de eredivisie is: {clubs.nummer1}</div>
            <div>De nummer 2 club van de eredivisie is: {clubs.nummer2}</div>
            <div>De nummer 3 club van de eredivisie is: {clubs.nummer3}</div>
        </div>
    )
};
export default MyPersonalComponent

Empowering State Management with useReducer:

The useReducer hook, when coupled with useContext, transforms your application into a centralized store, akin to Redux. Redux, a popular state management solution, becomes indispensable as your application scales. However, useReducer offers a lightweight alternative to useState, particularly beneficial for handling complex state logic or dependencies.

To employ useReducer, you need to provide it with a reducer function and an initial state. The reducer function determines the new state based on the action type. Here's a simple example:


// VoteWidget.js
import React, { useReducer } from "react";
const initialState = {
    ajax: 10,
    psv: 4,
    vitesse: 6,
    feyenoord: 8
};
const reducer = (state, action) => {
    switch (action.type) {
        case 'ajax':
            return { ...state, ajax: state.ajax + 1 };
        case 'psv':
            return { ...state, psv: state.psv + 1 };
        case 'vitesse':
            return { ...state, vitesse: state.vitesse + 1 };
        case 'feyenoord':
            return { ...state, feyenoord: state.feyenoord + 1 };
        default:
            throw new Error();
    }
}


const VoteWidget = () => {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
        <div>
             <h1>Stem op je favoriete club!</h1>
            Ajax: {state.ajax}
            <button onClick={() => dispatch({ type: 'ajax' })}>Ajax</button>
            PSV: {state.psv}
            <button onClick={() => dispatch({ type: 'psv' })}>PSV</button>
            Vitesse: {state.vitesse}
            <button onClick={() => dispatch({ type: 'vitesse' })}>Vitesse</button>
            Feyenoord: {state.feyenoord}
           <button onClick={() => dispatch({ type: 'feyenoord' })}>Feyenoord</button>
        </div>
    );
}
export default VoteWidget

Incorporating useContext and useReducer into your React development toolkit opens up new avenues for efficient state management and context sharing. As you embark on your React journey, mastering these hooks will undoubtedly enhance your ability to build scalable and maintainable applications.
Stay tuned for more insights into the world of React hooks in our upcoming articles. Happy coding!

Read some of our blogs down here!

Expand your knowledge with the 4BIS Blog...

5 Tips to Find the Right Software Developer

Web development, Software Modernisation, Ecommerce / Webshop, Business software, PHP, MySQL, HTML & CSS

Discover 5 essential tips for finding the right software developer, from price-quality ratio to location and experience. Read our helpful guide!

Read more

Automating your Software and Processes: Benefits and Applications

Automate, Web development, Software Modernisation, Business software, Knowledge Base

Discover how automation of your software and processes can improve your business. Learn about the benefits of automation and how it can make your operations more efficient. Contact us for customized automation solutions.

Read more

WooCommerce made functional on both mobile and desktop

Automate, Web development, Software Modernisation, Knowledge Base, WordPress, WooCommerce

Learn how to change backend behavior on a WordPress website for mobile devices with 4BIS Innovatives' expert guide. Discover tips on optimizing your WordPress site's performance by adjusting backend settings specifically for mobile users. Explore how...

Read more

And what can we do for you?_

Do you want to know more or are you interested? Please feel free to contact us directly, by phone or via mail.
Or use one of our contact forms so that we can answer you as quickly and appropriately as possible can give. We would love to hear from you!

back to top