简体   繁体   中英

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>;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM