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();

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.

Alt Text

Implementations

Articles

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

Posted on by:

jenhsuan profile

Jen-Hsuan Hsieh

@jenhsuan

6+ year work experience in the software engineering field. 2+ year work experience with front-end JavaScript framework like React.js, Knockout.js. and Microsoft solution.

Discussion

markdown guide