Introduction
The simple solution to solve props drilling in ReactJS is to use Context APIs. It's a convenient way to use global states instead of Redux.
Introduction to Context APIs
There are three roles from React library.
1.React.createContext
const ShoppingCartContext = createContext();
2.React.useReducer:
- Inputs: it accepts a reducer function and a initial state.
// Reducer function: changes the state with action
(state, action) => newState
//initial state
const initState = {
products: [],
}
- Outputs: it generates dispatch functions and new states. They will be values of context provider.
3.React.useContext:
- The React component will call the dispatch functions with actions to change the states in the context provider. The React component can also retrieve the states with using useContext
const shoppingCartContext = React.useContext(ShoppingCartContext);
These is a simple digram for React components and Context APIs.
Implementations
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
Top comments (0)