50

TypeScript-aware React hooks for global state

 5 years ago
source link: https://www.tuicool.com/articles/hit/vQN322a
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
rUFb2q3.png!web

React Hooks API is a new proposal for React v16.7. It enables writing all components as functions with full functionality. You can develop “custom hooks” to add a new functionality. Although it’s not released yet, I would like to introduce a new library to support global state. Note that it’s still an experiment.

The library

It’s called “react-hooks-global-state” and is available in npm . Please also checkout the GitHub repository.

How to code with it

Firstly, you need to define a global state and export custom hooks.

import { createGlobalState } from 'react-hooks-global-state';

const { stateItemHooks } = createGlobalState({
  counter: 0,
  person: {
    age: 0,
    firstName: '',
    lastName: '',
  },
});

export const {
  counter: useGlobalStateCounter,
  person: useGlobalStatePerson,
} = stateItemHooks;

Then, use one of the hooks to implement a Component.

import * as React from 'react';

import { useGlobalStateCounter } from './state';

const Counter = () => {
  const [value, update] = useGlobalStateCounter();
  return (
    <div>
      <span>
        Count:
        {value}
      </span>
      <button type="button" onClick={() => update(v => v + 1)}>+1</button>
      <button type="button" onClick={() => update(v => v - 1)}>-1</button>
    </div>
  );
};

export default Counter;

Even if you use the Counter component twice, they share the state.

import * as React from 'react';

import Counter from './Counter';
import Person from './Person';

const App = () => (
  <div>
    <h1>Counter</h1>
    <Counter />
    <Counter />
  </div>
);

export default App;

You can try this example by cloning the repository and run:

npm run examples:typescript

Is this TypeScript?

Actually, yes! It’s fully typed, and furthermore there’s no implicity any type in the code. The example code is written in TypeScript, but the library itself is written in JavaScript with type definition, so you can use it either way as you like.

Any feedbacks?

Any feedbacks are appreciated via Medium, Twitter or GitHub issues. Thanks!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK