Using state without useHookstate hook
You can use Hookstate without a hook. It is particularly useful for integration with old class-based React components. It works with global, local, nested and scoped states the same way.
The following example demonstrates how to use a global state without useHookstate hook:
Current state: 0import React from 'react';import { hookstate, StateFragment } from '@hookstate/core';const state = hookstate(0);export const ExampleComponent = () => <StateFragment state={state}>{s => <span>Current state: {s.value} <button onClick={() => s.set(p => p + 1)}>Increment</button></span>}</StateFragment>
And the following components are identical in behavior:
Functional component:
const globalState = hookstate('');
const MyComponent = () => {
const state = useHookstate(globalState);
return <input value={state.value}
onChange={e => state.set(e.target.value)} />;
}
Functional component without a hook:
const globalState = hookstate('');
const MyComponent = () => <StateFragment state={globalState}>{
state => <input value={state.value}
onChange={e => state.set(e.target.value)}>
}</StateFragment>
Class-based component:
const globalState = hookstate('');
class MyComponent extends React.Component {
render() {
return <StateFragment state={globalState}>{
state => <input value={state.value}
onChange={e => state.set(e.target.value)}>
}</StateFragment>
}
}