Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a shared state between two react components?

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 updated, I want to redirect to component B, where the user adds some more inputs and updates the same state as component A to build an object with inputs from A and B before I submit a post request to my api to save the data from both component A and B. How can I accomplish this, is there a way to use react-router, or do I have to set up a parent/child relationship between the components?

like image 380
Jack Avatar asked Aug 11 '16 15:08

Jack


People also ask

How do I share a state between components in React redux?

Another way to share data between multiple components is to use a state management solution. A popular state management solution for React apps is Redux and React-Redux. In index. js , we have the rootReducer with that takes the state value and return the latest value of the store based on the action type we dispatch.

Can we use state in another component?

To use the same state in several components, you have to: Lift the state up to the closest common ancestor. Pass down the state variable and the function to update this state in the props.


3 Answers

The dependency type between the components will define the best approach.

For instance, redux is a great option if you plan to have a central store. However other approaches are possible:

  • Parent to Child

    1. Props
    2. Instance Methods
  • Child to Parent

    1. Callback Functions
    2. Event Bubbling
  • Sibling to Sibling

    1. Parent Component
  • Any to Any

    1. Observer Pattern
    2. Global Variables
    3. Context

Please find more detailed information about each of the approaches here

like image 86
Custodio Avatar answered Oct 23 '22 21:10

Custodio


What you want is to implement some object that stores your state, that can be modified using callback functions. You can then pass these functions to your React components.

For instance, you could create a store:

function Store(initialState = {}) {
  this.state = initialState;
}
Store.prototype.mergeState = function(partialState) {
  Object.assign(this.state, partialState);
};

var myStore = new Store();

ReactDOM.render(
  <FirstComponent mergeState={myStore.mergeState.bind(myStore)} />,
  firstElement
  );
ReactDOM.render(
  <SecondComponent mergeState={myStore.mergeState.bind(myStore)} />,
  secondElement
  );

Now, both the FirstComponent and SecondComponent instances can call this.props.mergeState({ . . .}) to assign state to the same store.

I leave Store.prototype.getState as an exercise for the reader.

Note that you can always pass the store (myStore) itself to the components; it just feels less react-y to do so.

Here is some more documentation that might be of interest:

React Docs: "Communicate Between Components"

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this.

like image 31
A. Vidor Avatar answered Oct 23 '22 20:10

A. Vidor


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 (
    <p>
      Username: <input value={username} onChange={(ev) => setUsername(ev.target.value)} />
    </p>
  );
};

const ComponentB = () => {
  // Use  the shared hook!
  const { email, setEmail } = useSharedFormState();
  return (
    <p>
      Email: <input value={email} onChange={(ev) => setEmail(ev.target.value)} />
    </p>
  );
};

const ComponentC = () => {
  // Use shared hook!
  const { email, username } = useSharedFormState();
  return (
    <p>
      Username: {username} <br />
      Email: {email}
    </p>
  );
};

export const App = () => (
  <>
    <ComponentA />
    <ComponentB />
    <ComponentC />
  </>
);
  • 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.

like image 9
Slava Birch Avatar answered Oct 23 '22 22:10

Slava Birch