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

Artificial Intelligence vs Machine Learning: This is the Difference

Software Modernisation, Knowledge Base, Automate, Web development

Nowadays, many terms are thrown around interchangeably. You sometimes hear about Artificial Intelligence, but also about Machine Learning and perhaps even Deep Learning. This can make it quite unclear what exactly the term is that you are looking for...

Read more

5 Reasons Why You Want to Connect All Your Tools

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

Integrations are extremely important to ensure smooth collaboration between all your tools. Unfortunately, it still often happens that companies make some activities run less smoothly by not properly linking their tools. This is of course a shame because...

Read more

No secure server connection: These are the most common connection errors

Knowledge Base

Error messages when looking up a website are common. Although they are often easy to solve, they still often go wrong. This could be due to a small error, but this can immediately prevent a connection error. Resolving these errors requires some steps....

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