DEV Community

Cover image for React: Not Everything is State
Dylan Paulus
Dylan Paulus

Posted on • Edited on

5 2

React: Not Everything is State

[Quick Tip]

When working with React we get introduced to state as a way if storing component's data. There is another way that generally gets overlooked: class properties.

Example

class AnnoyingButton extends React.Component {
    intervalId = null; // Here!
    id = generateUniqueId(); // Here!

    state = {
        isDisabled: false
    };

    componentDidMount() {
        this.intervalId = setInterval(() => {
            this.setState(({ isDisabled }) => ({
                isDisabled: !isDisabled
            }));
        }, 100);
    }

    componentWillUnmount() {
        console.log(`Unmounting ID: ${this.id}`);
        clearInterval(this.intervalId);
    }

    render() {
        return <button disabled={this.state.isDisabled} />;
    }
}
Enter fullscreen mode Exit fullscreen mode

Nothing special about the component; the interesting bits are the id and intervalId variables. We need some way of preventing memory leaks when the component unmounts. In componentDidMount we save the interval's ID to a class property. Then, use the property to clear the interval and console.log the component's unique ID.

You might be thinking, "Why chouldn't we just store this information in the component's state?" React re-renders the component, and any child components, when the state changes. If the render method never uses a piece of the state it could be causing unwanted renders--making your application slower!

When to use class properties: If state needs to be stored, but is never used as a part of the view/render of a component.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
aralroca profile image
Aral Roca

I'm always using this approach to storage intervals and timeouts to then clean it on willUnmount 😄

In fact, is better to only storage values directly to the state when after change this value you expect to refresh the DOM.

Short article but great 😉

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay