Is it possible to share states between components using the useState() hook in React?

后端 未结 7 1342
春和景丽
春和景丽 2020-12-13 00:19

I was experimenting with the new Hook feature in React. Considering I have the following two components (using React Hooks) -

const HookComponent = () =>         


        
7条回答
  •  温柔的废话
    2020-12-13 00:41

    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.

提交回复
热议问题