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...

WordPress and Plugins – A world that opens up for you!

WordPress, Web development, Ecommerce / Webshop, Knowledge Base, WooCommerce

With plugins you can expand the functionality of WordPress or add completely new functions to WordPress. You can make plugins yourself, provided you know PHP, or you can download them.

Read more

Unveiling Tech-Nieuws.nl: Where Innovation Meets Ingenuity

SEO / SEA, Software Modernisation, Web development, PHP, Symfony, Digital Marketing

In the bustling realm of technology, staying updated is not just a necessity but a lifestyle. With an overflow of information bombarding us daily, having a reliable source to curate and present the latest tech news becomes invaluable. Enter Tech-Nieuws.nl,...

Read more

HR software: This is how you automate Human Resource Management

Business software, Software Modernisation, Web development, Automate

HRM, also known as Human Resource Management, is an important part for every company. Especially if you have many employees, an HR department is indispensable. However, it is not necessary to have a huge HR department. Much can be automated using HR...

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