Simple React useState and context like state management library for Longwood
You can use the createState
function to create a useState
function:
const app = createRenderTarget()
const useState = createState(0)
const render = div(
useState((state, setState) =>
div(
text(`Count: ${state}`),
button({
id: 'button',
onclick: () => setState(state + 1),
children: [text('+1')]
})
)
)
)
The useState
function exposes state
and setState
arguments to the
callback, which you can use to manage your component-specific state.
You can use createContext
function to craete a context object with state:
const { provider, consumer } = createContext(0)
const render = provider(
div(
consumer((state, setState) =>
div(
text(`Count: ${state}`),
button({
onclick: () => setState(state + 1),
children: [text('+1')]
})
)
)
)
)
render(app)
You can then modify the state and the provider automatically re-renders the DOM.
You can check out a full TODO app example:
longwood-usestate
is available as ES module, so quickest way to get started is
to import the module directly within your HTML page:
<html>
<body>
<div id="app"></div>
<script type="module">
import { div, button } from 'https://cdn.skypack.dev/longwood'
import { createState } from 'https://cdn.skypack.dev/longwood-usestate'
const useState = createState(0)
const render = div(
useState((state, setState) =>
div(
text(`Count: ${state}`),
button({
onclick: () => setState(state + 1),
children: [text('+1')]
})
)
)
)
render(document.getElementById('app'))
</script>
</body>
</html>
This is literally all the code you'll need! No build tools needed, no extra steps, just save the code as a .html file and start hacking.
You can install longwood-usestate
to your project like a normal dependency
within your project:
yarn add longwood longwood-usestate
Then you can import the package in your js file. For example if you're using Webpack, you can do:
import { div } from 'longwood'
import { useState } from 'longwood-usestate'
const useState = createState(0)
const render = div(
useState((state, setState) =>
div(
text(`Count: ${state}`),
button({
onclick: () => setState(state + 1),
children: [text('+1')]
})
)
)
)
render(document.getElementById('app'))
You can use TDD for development by running:
yarn
yarn test --watch
This runs Jest, and the tests use JSDOM for asserting how DOM looks like.
You can build the project by running:
yarn build
This builds the project into build/
directory.
This project is automatically deployed to NPM by using Travis CI. All tagged versions are published when pushed.
Don't add tags by hand! Run:
yarn release
This will run an interactive deploy script to help you deploy the most recent version.
This is a very early version of the project, and all feedback is welcome. Please open an issue before implementing, as the direction still needs some adjustments.
The code in this project is licensed under MIT license.