DEV Community

Cover image for Day 2 of #100DaysOfCode: Create a ReactJS global states manager with React hooks
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on • Updated on

Day 2 of #100DaysOfCode: Create a ReactJS global states manager with React hooks

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();
Enter fullscreen mode Exit fullscreen mode

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: [],
}
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode

These is a simple digram for React components and Context APIs.

Alt Text

Implementations

Articles

There are some of my articles. Feel free to check if you like!

Top comments (0)