I was experimenting with the new Hook feature in React. Considering I have the following two components (using React Hooks) -
const HookComponent = () =>
This is possible using the useBetween
hook.
See in codesandbox
import React, { useState } from 'react';
import { useBetween } from 'use-between';
const useShareableState = () => {
const [username, setUsername] = useState('Abrar');
const [count, setCount] = useState(0);
return {
username,
setUsername,
count,
setCount
}
}
const HookComponent = () => {
const { username, setUsername, count } = useBetween(useShareableState);
const handleChange = (e) => {
setUsername(e.target.value);
}
return (
{username}
From HookComponent: {count}
)
}
const HookComponent2 = () => {
const { count, setCount } = useBetween(useShareableState);
return (
You clicked {count} times
);
}
We move React hooks stateful logic from HookComponent
to useShareableState
.
We call useShareableState
using useBetween
in each component.
useBetween
is a way to call any hook. But so that the state will not be stored in the React component.
For the same hook, the result of the call will be the same. So we can call one hook in different components and work together on one state. When updating the shared state, each component using it will be updated too.