DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Guide To React Context With Functional Component Using Hooks

By leveraging the useContext React Hook, we can subscribe to the context in any functional component. Learn more here.

Saurabh Dashora user avatar by
Saurabh Dashora
CORE ·
Apr. 07, 22 · Tutorial
Like (4)
Save
Tweet
Share
3.98K Views

Join the DZone community and get the full member experience.

Join For Free

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:

ButtonTheme.jsimport 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 the 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. The same argument can also be used to pass multiple values in React Context.

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.

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

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Getting a Private SSL Certificate Free of Cost
  • What Is Advertised Kafka Address?
  • Top 5 Data Streaming Trends for 2023
  • Rust vs Go: Which Is Better?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: