If you are referring to component state, then hooks will not help you share it between components. Component state is local to the component. If your state lives in context, then useContext hook would be helpful.

Fundamentally, I think you misunderstood the line "sharing stateful logic between components". Stateful logic is different from state. Stateful logic is stuff that you do that modifies state. For e.g., a component subscribing to a store in componentDidMount() and unsubscribing in componentWillUnmount(). This subscribing/unsubscribing behavior can be implemented in a hook and components which need this behavior can just use the hook.

If you want to share state between components, there are various ways to do so, each with its own merits:

1. Lift State Up

Lift state up to a common ancestor component of the two components.

function Ancestor() {
    const [count, setCount] = useState(999);
    return <>
      <DescendantA count={count} onCountChange={setCount} />
      <DescendantB count={count} onCountChange={setCount} />
    </>;
  }

This state sharing approach is not fundamentally different from the traditional way of using state, hooks just give us a different way to declare component state.

2. Context

If the descendants are too deep down in the component hierarchy and you don't want to pass the state down too many layers, you could use the Context API.

There's a useContext hook which you can leverage on within the child components.

3. External State Management Solution

State management libraries like Redux or Mobx or Zustand. Your state will then live in a store outside of React and components can connect/subscribe to the store to receive updates.

Answer from Yangshun Tay on Stack Overflow
Top answer
1 of 10
164

If you are referring to component state, then hooks will not help you share it between components. Component state is local to the component. If your state lives in context, then useContext hook would be helpful.

Fundamentally, I think you misunderstood the line "sharing stateful logic between components". Stateful logic is different from state. Stateful logic is stuff that you do that modifies state. For e.g., a component subscribing to a store in componentDidMount() and unsubscribing in componentWillUnmount(). This subscribing/unsubscribing behavior can be implemented in a hook and components which need this behavior can just use the hook.

If you want to share state between components, there are various ways to do so, each with its own merits:

1. Lift State Up

Lift state up to a common ancestor component of the two components.

function Ancestor() {
    const [count, setCount] = useState(999);
    return <>
      <DescendantA count={count} onCountChange={setCount} />
      <DescendantB count={count} onCountChange={setCount} />
    </>;
  }

This state sharing approach is not fundamentally different from the traditional way of using state, hooks just give us a different way to declare component state.

2. Context

If the descendants are too deep down in the component hierarchy and you don't want to pass the state down too many layers, you could use the Context API.

There's a useContext hook which you can leverage on within the child components.

3. External State Management Solution

State management libraries like Redux or Mobx or Zustand. Your state will then live in a store outside of React and components can connect/subscribe to the store to receive updates.

2 of 10
96

It is possible without any external state management library. Just use a simple observable implementation:

function makeObservable(target) {
  let listeners = []; // initial listeners can be passed an an argument aswell
  let value = target;

  function get() {
    return value;
  }

  function set(newValue) {
    if (value === newValue) return;
    value = newValue;
    listeners.forEach((l) => l(value));
  }

  function subscribe(listenerFunc) {
    listeners.push(listenerFunc);
    return () => unsubscribe(listenerFunc); // will be used inside React.useEffect
  }

  function unsubscribe(listenerFunc) {
    listeners = listeners.filter((l) => l !== listenerFunc);
  }

  return {
    get,
    set,
    subscribe,
  };
}

And then create a store and hook it to react by using subscribe in useEffect:

const userStore = makeObservable({ name: "user", count: 0 });

const useUser = () => {
  const [user, setUser] = React.useState(userStore.get());

  React.useEffect(() => {
    return userStore.subscribe(setUser);
  }, []);

  const actions = React.useMemo(() => {
    return {
      setName: (name) => userStore.set({ ...user, name }),
      incrementCount: () => userStore.set({ ...user, count: user.count + 1 }),
      decrementCount: () => userStore.set({ ...user, count: user.count - 1 }),
    }
  }, [user])

  return {
    state: user,
    actions
  }
}

And that should work. No need for React.Context or lifting state up

🌐
React
react.dev › learn › sharing-state-between-components
Sharing State Between Components – React
This principle is also known as having a “single source of truth”. It doesn’t mean that all state lives in one place—but that for each piece of state, there is a specific component that holds that piece of information. Instead of duplicating shared state between components, lift it up to their common shared parent, and pass it down to the children that need it.
Discussions

Sharing data between React components - javascript
I have a search form in React that performs an API call and saves the data called nameservers in-state using the useState() React hook. I'm trying to determine how I can pass this data to another component so the data can be used for rendering elsewhere on the page. More on stackoverflow.com
🌐 stackoverflow.com
July 19, 2020
How to share state between hooks?
You're going to want to look at useContext it's the hook way of handling Providers/Consumers More on reddit.com
🌐 r/reactjs
11
1
May 2, 2019
How can I pass data between sibling components in React?
If your project is large, you can simply do it using useContext React hook. Here, let me explain steps to share data between sibling components. More on github.com
🌐 github.com
7
5
July 17, 2024
how to you share state between sibling components?
You need to research the concept of 'lifting state'. https://reactjs.org/docs/lifting-state-up.html The parent component can hold the state of its' children, in this case the sibling components you want to share data between. The parent will provide its' state to the children components as props. The parent can also pass functions down as props that will allow the children to update the shared state. When a child updates the parent's state, the new values will propagate to the other sibling through its' own props. There is absolutely no need for Context or Redux here. When I'm trying to solve a problem, I'm mindful if things are getting too complex, as it's usually an indication I'm doing it wrong. Hope this helps. More on reddit.com
🌐 r/reactjs
16
0
January 31, 2023
🌐
DEV Community
dev.to › frankiesardo › share-state-using-custom-hooks-5245
Share state using custom hooks - DEV Community
August 17, 2021 - Custom hooks that encapsulate caching are also a great way to share data between components: user, preferences, and remote data all reside in-memory and only need to be fetched once.
🌐
LogRocket
blog.logrocket.com › home › using react hooks for state management
Using React Hooks for state management - LogRocket Blog
June 4, 2024 - Using the useReducer Hook for state management in React enables you to share state between components without Redux.
🌐
DEV Community
dev.to › betula › sharing-react-hooks-stateful-logic-between-components-1g3o
Sharing React hooks stateful logic between components - DEV Community
January 21, 2021 - But If you want to share It with sibling one level components or a set of scattered components, you will be frustrated. useBetween hook is the solution to your problem 😚 · // App.jsx import React, { useState, useCallback } from 'react'; ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-share-state-across-react-components-with-context
How To Share State Across React Components with Context | DigitalOcean
July 22, 2020 - Any wrapped child components will have access to data from the Provider with the useContext Hook. Since the user data will be constant across the project, put it as high up the component tree as you can. In this application, you will put it at the root level in the App component: ... import ...
Find elsewhere
🌐
DEV Community
dev.to › bytebodger › hacking-react-hooks-shared-global-state-553b
Hacking React Hooks: Shared Global State - DEV Community
July 29, 2020 - Leverage the same old techniques that we could always use in class-based components (with the same drawbacks), Or they veer off into complex-and-abstract solutions that are obtuse and potentially brittle. In the "same story, different day" category, Hooks have excellent support for the Context API. And this can certainly be extremely useful. But the Context API can't share state between two sibling components unless the state is saved higher up the chain.
🌐
Sivabharathy
sivabharathy.in › blog › best-ways-to-pass-data-between-components-on-react
Best Ways To Pass Data Between Components On React | Sivabharathy
January 28, 2025 - Custom hooks are especially useful when the same data or behavior is needed in multiple components. const useSharedData = () => { const [data, setData] = React.useState("Shared Hook Data"); return { data, setData }; }; const Component1 = () => { const { data, setData } = useSharedData(); return <button onClick={() => setData("Updated Hook Data!")}>Update</button>; }; const Component2 = () => { const { data } = useSharedData(); return <p>{data}</p>; };
Top answer
1 of 3
11

There are multiple ways to share data between components. You can use one of the following options:

  • If the component to which you want to pass the data is a child of SearchForm component, then you can pass it as a prop.

  • If you are managing state via redux, you can connect components to the redux store and get the required data from the redux store in your components.

  • You can also use React's Context API to share common data between components that may or may not have a parent-child relationship.

  • If the component that needs the data from SearchForm component, is a parent component of SearchForm component, you can pass a callback function to the SearchForm component as a prop and when data is available in SearchForm component, call the callback function, received as a prop, and pass the data as an argument to that callback function.

2 of 3
3

Ciao, when I want to share data between components I use React-Redux. Lets make an example: Suppose that you want to share data received by server (nameservers). At first install react-redux:

npm install react-redux
npm install redux
npm install @reduxjs/toolkit

Now we have to create the reducer and the action: Lets say you have your component in a folder called "/components/MyComponent". Create a file called MyReducer.js.

/components/MyComponent/MyReducer.js

import { createReducer } from '@reduxjs/toolkit';

const initialState = {
  nameservers: undefined,
};

const LoginReducer = createReducer(initialState, {
   ["SET_NAMESERVERS"]: (state, action) => {
       state.nameservers= action.payload.nameservers;
   },
})

export default MyReducer;

Now, on the same folder, createa file called MyAction.js

/components/MyComponent/MyAction.js

export const setNameServers = data => ({
   type: "SET_NAMESERVERS",
   payload: { nameservers: data }
});

Then create the store: On your project root create a folder callled redux. Inside this create a folder called store. Then on this folder create a file called index.js.

redux/store/index.js

import { createStore, combineReducers } from "redux";
import MyReducer from '../../components/MyComponent/MyReducer';

const reducers = combineReducers({
  MyReducer,
});

const store = createStore(reducers);

export default store;

Now on index.js file on root folder lets pass the store already created:

index.js

...
import { Provider } from 'react-redux';
import store from "./redux/store";

ReactDOM.render((
 <Provider store={store}>
    <App />
 </Provider>
), document.getElementById('root') || document.createElement('div'));

We have almost done. On your component (MyComponent) you retrieve data from server. Once you have data, lets dispatch data to share into the store:

/components/MyComponent/MyComponent.js

...
import { useDispatch } from 'react-redux';
import { setNameServers } from './MyComponentAction';

const MyComponent: React.FC = () => {
   const [nameservers, setNameservers] = useState([]);
   const dispatch = useDispatch();
   ....
   const handleSubmit = (event: any) => {
     ...

fetch(`https://dns.google.com/resolve?name=${domain}&type=NS`)
.then(results => results.json())
.then(data => { 
  setLoading(false);
  if (data && data.Answer) {
    data.Answer.sort((a: any, b: any) => a.data.localeCompare(b.data));
    setNameservers(data.Answer);
    dispatch(setNameServers(data.Answer)); // here the magic
  } 
  });
 };
   
};

Done! now you have nameservers on your react redux store and you can easly get it from another component like this:

OtherComponent.js

import { useSelector } from 'react-redux';
const OtherComponent: React.FC = () => {
   const nameservers = useSelector(state => state.MyReducer.nameservers);
};

And if you log nameservers somewhere in OtherComponent you will see data retrieved in MyComponent. Awesome!

🌐
GitHub
github.com › betula › use-between
GitHub - betula/use-between: Sharing state between React components
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.
Starred by 291 users
Forked by 15 users
Languages   TypeScript 98.7% | JavaScript 1.3% | TypeScript 98.7% | JavaScript 1.3%
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Use React Context to Share Data between Components | Pluralsight
April 24, 2024 - Depending on your use case, you might prefer to use simple props, React Context or even a third-party library like Redux to share data between your components. Those three solutions are perfectly valid and production-ready. React Context official documentation · Typechecking with prop-types · Some React hooks are used in this article, here is their documentation ·
🌐
Medium
medium.com › @zachlandis91 › react-share-global-data-between-components-without-props-9f24abbcf208
React: Share “Global” Data Between Components Without Props | by Zach Landis | Medium
March 20, 2023 - To do this without the useContext hook, we’d have to set the user state (using the useState hook) in the App component and pass it down to the other components. Instead, we’ll reach into our handy React toolbox and use the useContext hook ...
🌐
Codementor
codementor.io › community › an example: use context and hooks to share state between different components
An Example: Use Context and Hooks to share state between different components | Codementor
August 22, 2019 - This example app here shows a recipe that you can use to keep such shared state in your application. ... We wrap the components within the Provider of this UsersContext. Individual components make use of useContext hook to get the value from ...
🌐
Medium
medium.com › sky-one-engineering › sharing-state-between-components-using-hooks-f10adef01952
Sharing state between components using hooks. | by Vitor Vieria | Sky.One Engineering | Medium
January 20, 2020 - But to this work, I need to import it inside of homeContainer and pass the state as props to starsFilter component. ... Ok, let’s build the movies catalog now with the same approach. ... I put some grids to make it responsible to have a better visual. Now, let’s import inside of homeContainer, pass the state as props and take a look at the result. ... And the result is. the following ... This way you are able to share state between components without controlling everything in the parent component and you also remove all the logic for an external layer and the components stays just as views.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-pass-data-from-one-component-to-other-component-in-reactjs
How to Pass Data from One Component to Another Component in ReactJS? | GeeksforGeeks
When you need to pass data between sibling components (components that share the same parent), the best way is to use their common parent component as a mediator. The parent component can manage the shared state and pass it down to both child ...
Published   March 24, 2025
🌐
GitHub
github.com › qosenergy › shared-store-hook
GitHub - qosenergy/shared-store-hook: Easily share state data between several React components. It's just like useState, but shared. · GitHub
Easily share state data between several React components. It's just like useState, but shared. - qosenergy/shared-store-hook
Starred by 3 users
Forked by 2 users
Languages   TypeScript 88.9% | JavaScript 10.9% | Shell 0.2%
🌐
Medium
medium.com › swlh › how-to-use-the-usereducer-react-hook-to-share-data-between-components-83123c9580a4
How to Use the useReducer React Hook to Share Data Between Components | by John Au-Yeung | The Startup | Medium
October 14, 2019 - Components in any other configuration like sibling or unrelated components can be done with the Context API. It lets you specify the provider for the data where you pass the data and a consumer to the data that is passed in by the provider. With the introduction of React hooks, there is an easier way to share data centrally between components situated in any configuration.