Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useEffect alternate for Class Component

Tags:

reactjs

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?

like image 975
arxoft Avatar asked Jun 26 '19 12:06

arxoft


People also ask

What is alternative of useEffect in class component?

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.

What can I use instead of hooks in class component?

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.

Is useEffect same as componentDidMount?

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() .

Can I use hook in class component?

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.


1 Answers

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.

like image 133
arxoft Avatar answered Oct 14 '22 16:10

arxoft