React Context is an important tool when it comes to sharing data between many components in a typical React application. While we can use React Context with Class Components, it is quite evident that more and more developers are moving to functional components. But can you use context with a functional component?

Yes, we can use React Context with a Functional Component. By leveraging the useContext React Hook, we can subscribe to the context in any functional component. However, there are a few important points to be kept in mind to use React Context with functional components.

1 – React Context Functional Component with useContext Hook

To demonstrate React Context in action for functional components, let us build a small demo application.

First, we will create the React Context. See below:

import React from 'react';

export const buttonThemes = {
    primary: {
        color: "white",
        background: "#45c496"
    },
    secondary: {
        color: "whitesmoke",
        background: "#d91b42"
    }
}

export const ButtonThemeContext = React.createContext(
    buttonThemes.primary
)

Basically, we define an object consisting of multiple themes such as primary and secondary.

Then, we use the React.createContext() function to initialize the context with a default value of primary theme. You can think of React context as a global variable that is available in the entire component tree covered by the Provider.

Next, we define the top-level component known as ContextDemoFC. This component will also have the Provider component.

export function ContextDemoFC() {
    const [ buttonTheme, setButtonTheme ] = useState(buttonThemes.primary);

    function changeTheme() {
        setButtonTheme( 
            buttonTheme === buttonThemes.primary
            ? buttonThemes.secondary
            : buttonThemes.primary
        )
    }

    return (
        <div>
            <ButtonThemeContext.Provider value={buttonTheme}>
                <ButtonContainer />
            </ButtonThemeContext.Provider>
            <button onClick={changeTheme}>Change Theme</button>
        </div>
    )
}

Basically, here we are using a React Functional Component. It has a local state variable known as buttonTheme. The user can change the theme by clicking the Change Theme button. The Change Theme button is tied to the changeTheme() function. This function basically toggles the buttonTheme between primary and secondary themes.

The important point here is the value prop that we pass to the ButtonThemeContext.Provider. Whenever the value prop changes, the entire component hierarchy within the Provider re-renders. In this example, we tie the value to the state variable buttonTheme.

Next, we have the ButtonContainer component. This is a very simple functional component.

function ButtonContainer() {
    return (
        <React.Fragment>
            <ThemedButton />
        </React.Fragment>
    )
}

Lastly, we have the React Context Consumer. See below:

function ThemedButton() {
    const theme = useContext(ButtonThemeContext);
    return(
        <button style={{ backgroundColor: theme.background, color: theme.color }}>Context Button</button>
    )
}

Here, we call the useContext React Hook to get access to the current context value. The useContext hook basically returns the value of the context. The hook also makes sure to re-render the component when the value of the context changes.

Once we obtain the context value, we can use it dynamically in the button styles.

2 – React Context Consumer vs useContext Hook

There is another approach to consume the React Context instead of the useContext hook. In the alternative approach, we use the Context.Consumer component.

See below example:

function ThemedButtonContextConsumer() {
    return (
        <ButtonThemeContext.Consumer>
            {( theme ) => (
                <button style={{ backgroundColor: theme.background, color: theme.color }}>Context Button</button> 
            )}
        </ButtonThemeContext.Consumer>
    )
}

Basically, in this case we wrap the button within ButtonThemeContext.Consumer.

The Context.Consumer requires a function as a child. This function accepts the current value of the context as input and returns the React node. The value argument (in this case, theme) is equal to the value prop in the Context.Provider component.

In case there is no Provider for the context, the value argument will contain the React Context Default Value that was assigned at the time of calling createContext.

When it comes to React Context Consumer vs useContext, it is far more preferable to utilize useContext. The useContext hook makes your consumer code far more readable in terms of syntax. React Context Consumer makes more sense in a class component since you cannot use a hook in a class component.

Conclusion

React Context with Functional Component works pretty seamlessly.

The useContext React Hook provides a clean syntax to access the current value of the Context from any nested component. However, we also looked at Context.Consumer approach to consume the context changes. It can also be used as an alternative approach.

Want to learn how to handle multiple values in React Context? Check out this post where we learn how to pass multiple values in React Context.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: ReactReact Hooks

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *