0

I'm using React 17 and I wonder why the following components does not behave equally. When using react component class, props inside methods are updated whereas with Functional component, they are not.

Using the React.Component class (visible props is updated inside check method)

class Clock extends React.Component {
    constructor(props) {
        super(props);
    }

    check() {
        console.log(this.props.visible);
    }

    componentDidMount() {
        this.timerID = setInterval(
            () => this.check(),
            5000
        );
    }

    componentWillUnmount() {
        clearInterval(this.timerID);
    }


    render() {
        return (
            <div />
        );
    }
}

Using function with hooks (visible props is NOT updated inside check method)

 function Comp(props) { // contains visible attr (false by default)
    const check = () => {
        console.log(props.visible); // stays as the default value when Comp mounted
    };

    useEffect(() => {
        const timerId = setInterval(() => {
            check();
        }, 5000);

        return () => clearInterval(timerId);
    }, []);

    return <div />;
}

Does anybody has an idea?

acorbel
  • 1,300
  • 12
  • 14
  • 2
    Possible duplicate of https://stackoverflow.com/questions/53024496/state-not-updating-when-using-react-state-hook-within-setinterval – Estus Flask Oct 31 '20 at 17:53
  • yup, stale closures - the above answer is a specific case for setInterval, and e.g. my answer in https://stackoverflow.com/a/58877875/1176601 contains more technical details – Aprillion Oct 31 '20 at 18:01

1 Answers1

2

hello if I understood your question well here is a solution to your problem https://codesandbox.io/s/crazy-wave-cj2n3?fontsize=14&hidenavigation=1&theme=dark and to explain what's the problem in your code u are not telling the child component to re-render when the props (visible) is changed and to do that u need to pass it in the array of useEffect function if you want to understand that more uncomment the line in App component and remove visible from useEffect you will see that the state is actually permuting from true to false in the parent but not in the child

mouheb
  • 99
  • 3