AimWhy / react-split-components

๐Ÿ A new way of Function Components without Hooks

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

kee.so

Create now โžซ ๐Ÿ”— kee.so


React Split Components (RiC)

A new way of React Components without Hooks.

English | ็ฎ€ไฝ“ไธญๆ–‡


Introduction

Introducing React Split Components โ†’

React Function Components in closure style.

Write React like Svelte, just natural and fluent code.

Features

  • Remove the dependence on Hooks, but not purely Functional Components
  • Only at the writing level, no need for ESLint support
  • Like High-Order Components, it's a "design pattern", not API, no lib needed

Simple Example

function demo({ atom }) {
  const state = atom({
    count: 0,
  });

  const onClick = () => {
    state.count += 1;
  };

  return () => {
    const { count } = state;
    return (
      <>
        <h1>{count}</h1>
        <button onClick={onClick}>Click me</button>
      </>
    );
  };
}

const Demo = create(demo);

Full Example

function demo({ props, atom, onMount, onEffect }) {
  const state = atom({
    // for useState
    loading: true,
    data: null,
    count: 0,

    // for useMemo
    power: () => state.count * state.count,
    text: () => `${props.theme} ~ ${state.count}`,
  });

  // for useRef
  const countRef = { current: null };

  // for useCallback
  const onClick = () => {
    const { setTheme } = props;
    setTheme();
    state.count += 1;
  };

  const getData = () => {
    request().then((res) => {
      state.data = res.data;
      state.loading = false;
    });
  };

  // for useEffect
  onMount(() => {
    getData();
    console.log('mount!');

    return () => {
      console.log('unmount!');
    };
  });

  onEffect(state.power, (val, prevVal) => {
    console.log('enter state.power', val, prevVal);

    return () => {
      console.log('clear state.power', val, prevVal);
    };
  });

  const onReload = () => {
    state.loading = true;
    getData();
  };

  return () => {
    const { theme } = props;
    const { loading, data, count, power, text } = state;

    return (
      <>
        <h1>{loading ? 'loading...' : JSON.stringify(data)}</h1>
        <button onClick={onReload}>Reload data</button>
        <h1>{theme}</h1>
        <h1 ref={countRef}>{count}</h1>
        <h1>{power}</h1>
        <h1>{text}</h1>
        <button onClick={onClick}>Click me</button>
      </>
    );
  };
}

const Demo = create(demo);

Online Demo

Edit react-split-components-final

License

MIT License (c) nanxiaobei

About

๐Ÿ A new way of Function Components without Hooks

License:MIT License


Languages

Language:JavaScript 100.0%