'Use React State in a hook with two separate exports

So i have created a hook which will act as a bridge between two different components. So the second function will take the data that the first function calculates and display them, however the first function will actually return a count of the displayed data.

These need to be connected with a state, since they should also update on change, those data can be deleted in the second function.

So what i want to do is, i want to setState in the second function and read it out in the first one. The way i did it now it won't work, since the useState is outside of a component.

How can i use this useState in both of these functions?

const [state, setState] = useState<string[]>([]);

export const thisUsesState = () => {
   return countOfArrayState;
}

export const thisUpdatesStateReturnsComponent = () => {
   return <Component></Component>;
}


Solution 1:[1]

Make a parent component for both the function and you can use state like a charm.

const Func: React.FC = () => {

const [state, setState] = useState<string[]>([]);

export const thisUsesState = () => {
   return countOfArrayState;
}

export const thisUpdatesStateReturnsComponent = () => {
   return <Component></Component>;
}
return something

}
export default Func

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ritik Banger