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

后端 未结 7 1336
春和景丽
春和景丽 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:47

    I've created hooksy that allows you to do exactly this - https://github.com/pie6k/hooksy

    import { createStore } from 'hooksy';
    
    interface UserData {
      username: string;
    }
    
    const defaultUser: UserData = { username: 'Foo' };
    
    export const [useUserStore] = createStore(defaultUser); // we've created store with initial value.
    // useUserStore has the same signature like react useState hook, but the state will be shared across all components using it
    

    And later in any component

    import React from 'react';
    
    import { useUserStore } from './userStore';
    
    export function UserInfo() {
      const [user, setUser] = useUserStore(); // use it the same way like useState, but have state shared across any component using it (eg. if any of them will call setUser - all other components using it will get re-rendered with new state)
    
      function login() {
        setUser({ username: 'Foo' })
      }
    
      return (
        
    {!user && You're logged out} {user && Logged as {user.username}}
    ); }

提交回复
热议问题