DEV Community

loading...
Cover image for Day 2 of #100DaysOfCode: Create a ReactJS global states manager with React hooks

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

jenhsuan profile image Jen-Hsuan Hsieh Updated on ・1 min read

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!

Discussion (0)

pic
Editor guide