1

I'd like to dispatch an action every second to update the display of a stateless component. My initial naive attempt involved calling window.setInterval in the render function, which is then called each time the component renders, starting a new timer each time.

I've considered closing over a variable that indicates whether or not the timer has already started, but that would violate the concept of a stateless component. I'm wondering what the appropriate way to accomplish this via React+Redux would be, ideally while continuing to use a stateless component.

w.brian
  • 16,296
  • 14
  • 69
  • 118
  • To answer you question properly more information is needed about your application and the "stateless" component. If the representation of a component depends on some value which updates frequently this is textbook definition for state. Why you want it to be stateless ? – Moti Korets Apr 23 '18 at 06:47

1 Answers1

2

Usually such operations made by using componentDidMount and componentWillUnmount lifecycle hooks. If you want to do it with Redux, you should implement it within container and pass your updated values into stateless component if you need it.

For instance:

class SomeContainer extends Component {

    _tick = () => {
        this.props.someAction()
    }

    render() {
        return <SomeComponent reduxValue={this.props.someValueFromRedux} />
    }

    componentDidMount() {
        this.timer = setInterval(this._tick, 1000)
    }

    componentWillUnmount() {
        clearInterval(this.timer)
    }
}

const mapStateToProps = ({ someReducer }) => {
    return {
        someValueFromRedux: someReducer.someValueFromRedux
    }
}

export default connect(mapStateToProps, { someAction })(SomeContainer)
Denys Kotsur
  • 2,579
  • 2
  • 14
  • 26