React JS — useContext API
Why Context API is used?
In react applications, we will usually use props to pass the data from parent to child component but context is the alternative way to pass the data between components without passing it as a prop.
Context is used to pass the widely used data in the application such as theme, user data, configurations, settings, locale details etc. context values can be easily accessed anywhere from the context child components hierarchy.
Similarly like one to many communication (broadcast), context also has provider and consumers. one provider can be connected with multiple consumers to pass the data. whenever the provider is updating the context value all the consumer components will be re-rendered to get the latest value. Only provider (sender) can update the context value and used across consumers (receivers).
Context can be created and used using 3 steps:
// Creating a context with a defaultValue
Context = create new context// Creating a context provider
Context.Provider
Child components @ Consumers
Context.Provider// Creating context consumer - Getting context value
context values = useContext (Context)
(or)
Context.Consumer
{ value => component}
Context.Consumer
I. Creating a context with a defaultValue
import { createContext } from 'react';export const Context = createContext('default value, its optional');
it’s safer to create a context always with a default value. The constant Context
will be exported and used to consume the context values from the consumer side, also the context instant will have the provider and consumer wrapper components that can be accessed by Context.Provider
and Context.Consumer
.
II. Creating a context provider
import { Context } from './filename';const [theme, setTheme] = useState('default value');onChangeTheme = () => { setTheme('new theme') }<Context.Provider value={theme}>
<ChildComponent />
</Context.Provider>
Default context value will be set while initialising itself. Provider will update the context value, whenever onChangeTheme()
function or setTheme()
function is called.
III. Creating a context consumers
Context values can be easily consumed in 2 ways
import { useContext } from 'react';
import { Context } from './filename';const contextValue = useContext(Context);
The constant contextValue
will have the theme details which is set by the context provider and here is the another way of consuming it is.
import { useContext } from 'react';
import { Context } from './filename';<Context.Consumer>
{contextValue => <button theme={contextValue}>Click</button>}
</Context.Consumer>
In this case the component will be wrapped by the context consumer that will provider a context value.