Skip to content

Instantly share code, notes, and snippets.

@stomita
Last active November 2, 2018 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stomita/3f308c414a2f409f47efeaef946a0de0 to your computer and use it in GitHub Desktop.
Save stomita/3f308c414a2f409f47efeaef946a0de0 to your computer and use it in GitHub Desktop.
This is a proposal of `createStateHook`, in order to eliminate call order magic and top-level restriction
import { createStateHook } from 'react';
export function createFormInputHook() {
const useValueState = createStateHook();
return (initialValue) => {
const [value, setValue] = useValueState(initialValue);
function onHandleChange(e) {
setValue(e.target.value);
}
return { value, onChange: onHandleChange };
}
}
import { createStateHook, createEffectHook } from 'react';
import { createFormInputHook } from './custom-hook-creator';
import ChatAPI from './ChatAPI';
const useCountState = createStateHook();
const useNameState = createStateHook();
const useIncrementEffect = createEffectHook();
const useStatusSubscriptionEffect = createEffectHook();
const useNameInput = createFormInputHook();
function Comp(props) {
const [count, setCount] = useCountState(0);
const [status, setStatus] = useStatusState(props.defaultStatus);
const { value: name, onChange: onChangeName } = useNameInput('Hana');
useIncrementEffect(() => {
const pid = setInterval(() => setCount(count+1), 1000);
return () => clearInterval(pid);
});
if (props.subscribeStatusUpdate) {
useStatusSubscriptionEffect(() => {
ChatAPI.subscribe(props.userId, setStatus);
return () => ChatAPI.unsubscribe(props.userId, setStatus);
}, [props.userId]);
}
return (
<>
<div>Count: {count}</div>
<div>Status: {status}</div>
<div>Name: <input type="text" onChange={onChangeName} value={name} /></div>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment