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
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 = () => (
<>
>
);
useFormState
custom hook as a source for our state.useSharedFormState
hook who uses useBetween
hook inside. That hook can be used in any component who can read or update the shared state!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.