iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🤖

Inter-component communication in React without Redux, Context API, Parent component logic, or Providers

に公開
2021/01/30

Data Communication Between Components

One of the initial hurdles in React is the exchange of data between components. When you try to share data across components, you typically need to create state in a parent component and distribute values or dispatch functions to each child component. Alternatively, this leads to using the ContextAPI or Redux, but since the amount of code you have to write upon introduction increases significantly, it comes with a considerable burden.

I will introduce a way to simplify this area.

*To use this, you need to install the package with a command such as:
yarn add -D @react-libraries/use-global-state

The code created for this article can be found at the following location:
https://github.com/SoraKumo001/use-global-state-sample01

Usage Example: A Program to Calculate BMI

*Note: Although Next.js is used here, useGlobalState itself works with plain React as well.

src/pages/index.tsx

import { useGlobalState } from '@react-libraries/use-global-state';
import React from 'react';

const Tall = () => {
  const [value, setValue] = useGlobalState('tall', '170');
  return (
    <div>
      Tall:
      <input
        value={value}
        onChange={(e) => {
          setValue(e.target.value);
        }}
      />
    </div>
  );
};
const Weight = () => {
  const [value, setValue] = useGlobalState('weight', '60');
  return (
    <div style={{ display: 'flex' }}>
      Weight:
      <input
        value={value}
        onChange={(e) => {
          setValue(e.target.value);
        }}
      />
    </div>
  );
};

const Bmi = () => {
  const [tall] = useGlobalState<string>('tall');
  const [weight] = useGlobalState<string>('weight');
  return (
    <div>
      {isNaN(Number(tall)) || isNaN(Number(weight))
        ? 'Error'
        : `BMI:${Math.floor((Number(weight) / Math.pow(Number(tall) / 100, 2)) * 100) / 100}`}
    </div>
  );
};

const Page = () => (
  <>
    <Bmi />
    <Tall />
    <Weight />
  </>
);
export default Page;

As the name suggests, useGlobalState is a global version Hook of useState. It allows data sharing across components. To use it, you don't need to have a component equivalent to a Provider, such as those found in Redux or ContextAPI, at a higher level in the tree. You can just write it and use it immediately. It's instantly wonderful.

If different initial values are set in multiple locations, useGlobalState adopts the initial value that was executed first. Also, if a call with an initial value is executed after a call without one, the component will be re-validated using that initial value.

Additionally, @react-libraries/use-global-state provides a mutate function, allowing you to set data from outside the components where useGlobalState is placed. This makes it possible to create components that send data but are not themselves targets for re-validation.

During test execution, you can import and run reset from @react-libraries/use-global-state to clear the stored data.

Easy Breezy

It is very easy because you don't have to write extra code for data or event communication.

GitHubで編集を提案

Discussion