Skip to content

Instantly share code, notes, and snippets.

@cristianoc
Last active December 23, 2018 18:04
Show Gist options
  • Save cristianoc/cef37bcfc0446da482da4723dc3319a8 to your computer and use it in GitHub Desktop.
Save cristianoc/cef37bcfc0446da482da4723dc3319a8 to your computer and use it in GitHub Desktop.
module HookTypes = {
type state('a);
type effect;
type t('t);
let addState: (t('t), ~state: 'state) => t(('t, state('state))) =
(x, ~state as _) => Obj.magic(x);
let addEffect: t('t) => t(('t, effect)) = Obj.magic;
};
let useState = (hooks, state) => {
let setState = x => ignore(x == state);
(hooks->(HookTypes.addState(~state)), state, setState);
};
let useEffect = (hooks, _functionWithEffects: unit => unit) =>
hooks->HookTypes.addEffect;
let functionComponent = (~message, ~hooks) => {
let (hooks, name, _setName) = hooks->(useState("Harry"));
let (hooks, surname, _setSurname) = hooks->(useState("Potter"));
let stringToRender = message ++ " " ++ name ++ " " ++ surname;
(hooks, stringToRender);
};
let customHookNameSurname = (hooks, ~initialName, ~initialSurname) => {
let (hooks, name, setName) = hooks->(useState(initialName));
let (hooks, surname, setSurname) = hooks->useState(initialSurname);
(hooks, name, setName, surname, setSurname);
};
let functionComponent2 = (~message, ~hooks) => {
let (hooks, name, _setName, surname, _setSurname) =
hooks->customHookNameSurname(
~initialName="Harry",
~initialSurname="Potter",
);
let stringToRender = message ++ " " ++ name ++ " " ++ surname;
(hooks, stringToRender);
};
let checkThatTheTwoFunctionsHaveTheSameType =
ignore(functionComponent == functionComponent2);
let effectBeforeState = (~hooks) => {
let hooks = hooks->useEffect(() => Js.log("About so use State"));
let (hooks, _name, _setName) = hooks->(useState("Harry"));
hooks;
};
let effectAfterState = (~hooks) => {
let (hooks, _name, _setName) = hooks->(useState("Harry"));
let hooks = hooks->useEffect(() => Js.log("Just Used State"));
hooks;
};
/*
let checkThatTheOrderMatters =
ignore(effectBeforeState == effectAfterState);
*/
/*
let thisDoesNotTypeCheck = (~message, ~hooks) => {
let (hooks, _name, _setName) =
Random.bool() ? "Harry" |> useState(~hooks) : (hooks, "", _ => ());
hooks;
};
*/
let theTypeCheckerIsSmart = (~message, ~hooks) => {
let (hooks, name, _setName, surname, _setSurname) =
Random.bool() ?
{
let (hooks, name, setName) = hooks->(useState("Harry"));
let (hooks, surname, setSurname) = hooks->(useState("Potter"));
(hooks, name, setName, surname, setSurname);
} :
hooks->customHookNameSurname(
~initialName="Harry",
~initialSurname="Potter",
);
let stringToRender = message ++ " " ++ name ++ " " ++ surname;
(hooks, stringToRender);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment