I`m having some problems trying to listen to state changes in this application. Basically I was expecting a useEffect hook to be fired after some state changed, but nothing at all is happening.
This is what I got
index.jsx
// this is a simplification.
// I actually have a react-router-dom's Router wrapping everything
// and App is a Switch with multiple Route components
ReactDOM.render(
<Provider>
<App>
</Provider>
, document.getElementById('root'));
useSession.jsx
export const useSession = () => {
const [session, setSession] = useState(null)
const login = useCallback(() => {
// do something
setSession(newSession)
})
return {
session,
setSession,
login
}
}
Provider.jsx
const { session } = useSession();
useEffect(() => {
console.log('Print this')
}, [session])
// more code ...
App.jsx
export function Login() {
const { login } = useSession();
return <button type="button" onClick={() => { login() }}>Login</button>
}
Well I have this Parent component Provider watching the session state, but when it is updated the useEffect of the provider is never called.
The useEffect
is fired only if the setSession
is called in the same hook/method. For example, if I import the setSession
in the Provider
and use it there, the useEffect
will be fired; Or if I add a useEffect
in the useSession
method, it is gonna be fired when login
updates the state.
The callback of useEffect
is called but only once, when the component is mounted, but not when the state is changed.
How can I achieve this behavior? Having the Provider
's useEffect
fired whenever session
is updated?
Thanks in advance!