I am trying to make my code clean and readable. So I decided to create a custom hook to store my useStates there. Then I created a new file to store my event listener. Now, I have three files: Page.js, useStates.js, and Listeners.js.
The problem is that I cannot use my states in event listeners.
I tried to store my states in global scope variables in useStates.js and pass them with getters. But it didn't work because updating the state didn't change the page(But it did rerender).
useStates.js:
import react, { useState } from 'react';
export default () => {
const [myState, setMyState] = useState(false);
return { myState, setMyState };
}
Page.js:
import react from 'react';
import useStates from './useStates';
import { someActionListener } from './listeners';
export default () => {
const states = useStates();
return <SomeComponent
somProp={states.myState}
onSomeAction={ someActionListener } />
}
Listeners.js:
export const someActionListener = (e) => {
// This should be done
states.setMyState(!states.myState);
}
onSomeAction={e => someActionListener(e, states)}