How to make a shared state between two react components?

前端 未结 5 497
盖世英雄少女心
盖世英雄少女心 2020-11-27 07:04

I have 2 react components that need to share a state, react-router shows component A, which takes some inputs and adds it to its state, after the state has been successfully

5条回答
  •  攒了一身酷
    2020-11-27 07:20

    The easiest way to use a shared state between several components without rewriting your application's code to some state management system is use-between hook.

    Try this example in codesandbox

    import React, { useState } from "react";
    import { useBetween } from "use-between";
    
    // Make a custom hook with your future shared state
    const useFormState = () => {
      const [username, setUsername] = useState("");
      const [email, setEmail] = useState("");
      return {
        username, setUsername, email, setEmail
      };
    };
    
    // Make a custom hook for sharing your form state between any components
    const useSharedFormState = () => useBetween(useFormState);
    
    const ComponentA = () => {
      // Use the shared hook!
      const { username, setUsername } = useSharedFormState();
      return (
        

    Username: setUsername(ev.target.value)} />

    ); }; const ComponentB = () => { // Use the shared hook! const { email, setEmail } = useSharedFormState(); return (

    Email: setEmail(ev.target.value)} />

    ); }; const ComponentC = () => { // Use shared hook! const { email, username } = useSharedFormState(); return (

    Username: {username}
    Email: {email}

    ); }; export const App = () => ( <> );
    • For first, we create useFormState custom hook as a source for our state.
    • In the next step, we create useSharedFormState hook who uses useBetween hook inside. That hook can be used in any component who can read or update the shared state!
    • And the last step is using useSharedFormState in our components.

    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.

提交回复
热议问题