React is a great library for building user interfaces. It lets us compose complex UIs from small and isolated pieces of code called Components. The heart of every React component is its “state”, an object that determines how that component renders & behaves. But managing the state can get very difficult as our application grows. There are many state management libraries like Redux which helps in managing global state but it’s not that easy to grasp, especially for a beginner.
Global State Management with Context API & Hooks:
Recently React has introduced Context API & Hooks. Now there isn’t a need to install any external library for managing State. We can manage the global state of our application via Context & Hooks.
Example: Let’s demonstrate this by taking a very basic example of using Context to pass data through the component tree without having to pass props down manually at every level.
We have a small React App which has two Component: Navbar.js & PageContent.js
We are Using a Switch Button to Switch between Dark & Light Theme.
Let’s use Context to share Theme Mode (Light / Dark) through entire app.
Steps of Global State Management with Context API & Hooks:
Step 1: Create a new file ThemeContext.js
Context is created by using React.createContext
ThemeContext is now a context Object. Every Context Object comes with a React Provider Component that allow the Consuming Component to consume the value of Provider.
It accepts a value prop in which we can pass the properties or methods to be used in Consuming Component.
We are passing darkMode property & toggleTheme Method to change the darkMode value in Context Provider.
Our ThemeContext.js will look like this:
We have used useState() Hook to set the state.
Our Context Provider i.e ThemeContext.Provider will be wrapped around all the component in which we want to access the value object i.e darkMode & method to toggle darkMode.
Step 2: Wrap all the component in which you want to access the value of Context Provider.
We have wrapped ThemeProvider around PageContent & Navbar Component.
Now the value of darkMode & method to toggle the darkMode will be accessible in PageContent & Navbar Component.
Step 3: Consuming the values in Navbar & PageContent Component
To consume the value of Context Provider we will use useContext() Hook which accepts a context object & returns the current context value for that context.
In our example, useContext will provide us darkMode value & toggleTheme method to toggle the darkMode Value.
We have used them to switch between both color theme.
Hooks & Context add a great value addition to the React Library. They are not just limited to managing global state. There are some great Hooks available in React Library which lets us using state & other React Feature in a functional Component.
Other Related Articles You Might Be Interested In