Posts

Showing posts from September, 2020

A new way to implement Redux-like global store with React Hooks and React Context

Image
In this article, I'm going to introduce a new way to implement a global store step by step by using React Hooks and React Context. The example code is available in  GitHub . 1. Initialize the project Let's create the project and install the dependencies. npx create-react-app react-context-hooks yarn install yarn start 2. Local store(state) Let's illustrate React local store in a simple counter example. There is a local state to manage the count variable, and a method - setCount to update it. It's quite straight forward, however it's restricted within the component to update count. What if we need to update from other components? React provides Context to achieve that. JavaScript 1 import React , { useState } from 'react' ; 2 3 function Counter () { 4   // Declare a new state variable, which we'll call "count" 5   const [ count , setCount ] = useState ( 0 ); 6 7   return ( 8     < div > 9       < p > You clicked { cou