What is Context API ?
The context API is a React structure that allows to exchange unique details. This API is used for context level data. This is an alternative for "Prop Drilling".
Context API is a new feature which is added to Version 16.3 in React. It allows to easily share the state across the entire app.
How the Context API works ?
React.createContext() is all you need. It returns a consumer and a provider. Provider is a component that provides the state to its children. It will hold the "store" and be the parent of all the components that might need that store. Consumer is a component that consumes and uses the state. More information can be found on React's documentation page.
How to use context API
- Create a folder under your app root named contexts (not required. just a convention)
- Create a file named <your context name>Context.js, e.g. userContext.js
- import and create a context like so:
import React, { createContext } from "react";
const UserContext = createContext();- Create a component that will wrap the provider named
Provider e.g. UserProvider
Example using React Hooks:
const UserProvider = ({ children }) => {
const [name, setName] = useState("John Doe");
const [age, setAge] = useState(1);
const happyBirthday = () => setAge(age + 1);
return (
<UserContext.Provider value={{ name, age, happyBirthday }}>
{children}
</UserContext.Provider>
);
};- Create a higher order component to consume the context named: with
e.g. withUser
Example using React Hooks:
const withUser = (Child) => (props) => (
<UserContext.Consumer>
{(context) => <Child {...props} {...context} />}
{/* Another option is: {context => <Child {...props} context={context}/>}*/}
</UserContext.Consumer>
);The difference between the two options above is if you want the context to be a single nested property by this name, to explode it to its properties (which in my opinion is more convenient).
- Finally export them
export { UserProvider, withUser };- And use them however you like
For example:
ReactDOM.render(
<UserProvider>
<App />
</UserProvider>,
document.getElementById("root")
);export default withUser(LoginForm);

Comments
Post a Comment