hoko v0.3.0
hoko
The jQuery for React.
A small library with utilities and shorthands for React.
Getting started
To get started, import the library as follows:
import * as $ from 'hoko';
To create your first state variable, use the $.state
function:
import * as $ from 'hoko'; // 225 B
function Component() {
const state = $.state({
count: 0,
});
return (
<div>
<h1>Count: {state.count}</h1>
<button onClick={() => state.count++}>Increment</button>
</div>
);
}
Installation
Install hoko from npm
with your package manager of your choice:
npm install hoko # npm
yarn add hoko # yarn
bun add hoko # bun
pnpm add hoko # pnpm
API
State management
$.state({ ... })
Creates a local state variable inside a React component. This allows for managing multiple state variables inside a single hook.
const state = $.state({
count: 0,
});
$.effect(() => {
console.log(state.count);
}, [state.count]); // the state as a dependency
console.log(state.count); // 0
state.count = 1; // updating the state
Alternatively, you can use the createState
exported from hoko
.
NOTE: Unfortunately, due to properties being a setter and getter pair, the state variable is mutable, but cannot be destructured.
- let { count } = $.state({ count: 0 });
$.globals({ ... })
Creates a global state variable, which is shared between all components.
Similarly to $.state
, the state variable is mutable, but cannot be
destructured.
const useState = $.globals({
count: 0,
});
function Component() {
const state = useState();
return (
<div>
<h1>Count: {state.count}</h1>
<button onClick={() => state.count++}>Increment</button>
</div>
);
}
Alternatively, you can use the createGlobals
exported from hoko
.
Helpers
$.rerender()
A function that can be used to force a re-render of a component.
const rerender = $.rerender();
rerender();
Shorthands
$.ref
A shorthand for React.useRef
that
passes null
as an argument by default.
$.id
A shorthand for React.useId
.
$.effect
or $.on
A shorthand for
React.useEffect
.
$.reducer
A shorthand for
React.useReducer
.
$.transition
A shorthand for
React.useTransition
.
License
MIT 💖