I just learned that in functional components I can use useEffect
to keep an eye on any side effect (ex: when using localStorage
) which makes sure my state is hooked up with the effect.
I want to have similar functionality in my class based Component for localStorage
. How can I make sure that my state updates itself as soon as there is any change into the localStorage
?
In a class component you will use the componentDidUpdate method to trigger some side-effect for this lifecycle. In the componentDidUpdate method you will receive the previous props and state so you can do a comparison between before and now.
While we cannot use a hook inside a class component, we could use one of two patterns for code reuse that works with them: Higher Order Components and Render Props.
Here's Why. It's very common to require some setup when a component is mounted to perform tasks like network calls. Before hooks were introduced we were taught to use functions like componentDidMount() .
You can't use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component.
This is how I did it.
class Login extends Component {
constructor(props) {
super(props);
this.state = {
// Get value from localStorage or use default
isLoggedIn: localStorage.getItem('isLoggedIn') || 0
}
// Listen to storage event
window.addEventListener('storage', (e) => this.storageChanged(e));
// Bind this to storageChanged()
this.storageChanged = this.storageChanged.bind(this);
}
storageChanged(e) {
if(e.key === 'isLoggedIn') {
this.setState({isLoggedIn: e.newValue})
}
}
render() {
return <p>{this.state.isLoggedIn}</p>
}
}
That's how I could hook into the localStorage
changes using class based component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With