A brief discussion on the state management method of React+Storeon

青灯夜游
Release: 2021-04-15 12:48:26
forward
2442 people have browsed it

This article will introduce you to the method of using event-driven state management in React. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on the state management method of React+Storeon

Since Hooks were introduced into React, the Context API and Hook library have been used together in application state management. But combining the Context API with Hooks (on which many Hooks-based state management libraries are built) may not be efficient for large-scale applications.

Since a custom Hook must be created to enable access to the state and its methods before it can be used in the component, it is cumbersome in actual development. This defeats the real purpose of Hooks: simplicity. But for smaller applications, Redux may seem too heavy.

Today we will discuss an alternative to the Context API: Storeon. Storeon is a tiny, event-driven state management library for React that works similarly to Redux. Use Redux DevTools to view and visualize state operations. Storeon internally uses Context API to manage state and adopts an event-driven approach for state operations.

[Related tutorial recommendations:React video tutorial]

Store

store is the data stored in the application state collection. It is created through thecreateStoreon()function imported from the Storeon library. The

createStoreon()function accepts a list of modules, where each module is a function that accepts astoreparameter and binds its event listener. Here is an example of a store:

import { createStoreon } from 'storeon/react' // todos module const todos = store => { store.on(event, callback) } export default const store = createStoreon([todos])
Copy after login

Modularity

The stores in Storeon are modular, that is, they are defined independently and are not Bind to a Hook or component. Each state and its operation methods are defined in functions called modules. These modules are passed into thecreateStoreon()function, which is then registered as a global store.

store has three methods:

  • store.get()– used to retrieve the current data in the state.

  • store.on(event, callback)– Used to register an event listener to the specified event name.

  • store.dispatch(event, data)– Used to emit events and pass in optional data based on defined event requirements.

Events

Storeon is an event-based state management library, and state changes are emitted by events defined in the state module. There are three built-in events in Storeon, they start with@. Other events are defined without the@prefix. The three built-in events are:

  • @init– This event is fired when the app loads. It is used to set the initial state of the app and execute anything in the callbacks passed to it.

  • @dispatch– This event fires on every new action. This is useful for debugging.

  • @changed– This event is fired when the application state changes.

Note: store.on(event, callback)is used to add event listeners in our module.

Demo program

To demonstrate how to perform application state operations in Storeon, we will build a simple notes program. Another package from Storeon will also be used to save state data inlocalStorage.

Assume you have basic knowledge of JavaScript and React. You can find the code used in this article athttps://github.com/Youngestde....

Setup

Before we dive in, let’s outline the project structure and installation of dependencies required by the Notes program. Start by creating the project folder.

mkdir storeon-app && cd storeon-app mkdir {src,public,src/Components} touch public/{index.html, style.css} && touch src/{index,store,Components/Notes}.js
Copy after login

Next, initialize the directory and install the required dependencies.

npm init -y npm i react react-dom react-scripts storeon @storeon/localstorage uuidv4
Copy after login

The next step is to write the parent component in theindex.jsfile.

index.js

This file is responsible for rendering our note component. First import the required packages.

import React from 'react' import { render } from 'react-dom'; function App() { return ( <> Hello!  ); } const root = document.getElementById('root'); render(, root);
Copy after login

Next build the store by writing code for initialization and manipulation of state instore.js.

store.js

This file is responsible for handling the state and subsequent state management operations in the application. We have to create a module to store state and support events to handle operational changes.

First, import thecreateStoreonmethod and unique random ID generator UUID from Storeon.

createStoreonmethod is responsible for registering our state to the global store.

import { createStoreon } from 'storeon'; import { v4 as uuidv4 } from 'uuid' import { persistState } from '@storeon/localstorage'; let note = store => {}
Copy after login

We store the status in the array variablenotes, which contains notes in the following format:

{ id: 'note id', item: 'note item' },
Copy after login

接下来,我们将用两个注释(在首次启动程序时会显示)来初始化状态,从而首先填充注释模块。然后,定义状态事件。

let note = store => { store.on('@init', () => ({ notes: [ { id: uuidv4(), item: 'Storeon is a React state management library and unlike other state management libraries that use Context, it utilizes an event-driven approach like Redux.' }, { id: uuidv4(), item: 'This is a really short note. I have begun to study the basic concepts of technical writing and I'\'m optimistic about becoming one of the best technical writers.' }, ] }); store.on('addNote', ({ notes }, note) => { return { notes: [...notes, { id: uuidv4(), item: note }], } }); store.on('deleteNote', ({ notes }, id) => ({ notes: notes.filter(note => note.id !== id), }); }
Copy after login

在上面的代码中,我们定义了状态,并用两个简短的注释填充了状态,并定义了两个事件和一个从dispatch(event, data)函数发出事件后将会执行的回调函数。

addNote事件中,我们返回添加了新 note 的更新后的状态对象,在deleteNote事件中把 ID 传递给调度方法的 note 过滤掉。

最后,把模块分配给可导出变量 store ,将其注册为全局 store,以便稍后将其导入到上下文 provider 中,并将状态存储在localStorage中。

const store = createStoreon([ notes, // Store state in localStorage persistState(['notes']), ]); export default store;
Copy after login

接下来,在Notes.js中编写 Notes 应用组件。

Notes.js

此文件包含 Notes 程序的组件。我们将从导入依赖项开始。

import React from 'react'; import { useStoreon } from 'storeon/react';
Copy after login

接下来,编写组件。

const Notes = () => { const { dispatch, notes } = useStoreon('notes'); const [ value, setValue ] = React.useState(''); }
Copy after login

在上面的代码的第二行中,useStoreon()hook 的返回值设置为可破坏的对象。useStoreon()hook 使用模块名称作为其参数,并返回状态和调度方法以发出事件。

接下来定义在组件中发出状态定义事件的方法 。

const Notes = () => { ... const deleteNote = id => { dispatch('deleteNote', id) }; const submit = () => { dispatch('addNote', value); setValue(''); }; const handleInput = e => { setValue(e.target.value); }; }
Copy after login

Let’s review the three methods we defined the above:
让我们回顾一下上面定义的三种方法:

  • deleteNote(id)– 此方法在触发时调度deleteNote事件。

  • submit()– 该方法通过传递输入状态的值来调度addNote事件,该状态在Notes组件中本地定义。

  • handleInput()– 此方法将本地状态的值设置为用户输入。

Next, we’ll build the main interface of our app and export it.
接下来,我们将构建应用程序的主界面并将其导出。

const Notes = () => { ... return ( 
Quick Notes