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 • Edited on

1 1

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay