|
Download react-use/docs/createGlobalState.md from Devendra174/react-code-dataset: direct link, hf CLI and curl.
- Browser
- Download file 1.21 kB
-
https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/main/react-use/docs/createGlobalState.md
- Command line
-
hf download hf://datasets/Devendra174/react-code-dataset/react-use/docs/createGlobalState.md
-
curl -L -o createGlobalState.md https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/main/react-use/docs/createGlobalState.md
1.21 kB
useGlobalState
A React hook that creates a globally shared state.
Usage
const useGlobalValue = createGlobalState<number>(0);
const CompA: FC = () => {
const [value, setValue] = useGlobalValue();
return <button onClick={() => setValue(value + 1)}>+</button>;
};
const CompB: FC = () => {
const [value, setValue] = useGlobalValue();
return <button onClick={() => setValue(value - 1)}>-</button>;
};
const Demo: FC = () => {
const [value] = useGlobalValue();
return (
<div>
<p>{value}</p>
<CompA />
<CompB />
</div>
);
};
It also allows initializing the state with a function and using a function in the setState:
const useGlobalValue = createGlobalState<number>(() => 0);
const CompA: FC = () => {
const [value, setValue] = useGlobalValue();
return <button onClick={() => setValue(value => value + 1)}>+</button>;
};
const CompB: FC = () => {
const [value, setValue] = useGlobalValue();
return <button onClick={() => setValue(value => value - 1)}>-</button>;
};
const Demo: FC = () => {
const [value] = useGlobalValue();
return (
<div>
<p>{value}</p>
<CompA />
<CompB />
</div>
);
};