Open
Description
Using preact-router
and the useEffect
hook won't properly trigger the returned function.
For example, if we transform the Clock
example from the Preact site (https://preactjs.com/guide/v10/components#class-components):
class Clock extends Component {
constructor() {
super();
this.state = { time: Date.now() };
}
// Lifecycle: Called whenever our component is created
componentDidMount() {
// update time every second
this.timer = setInterval(() => {
this.setState({ time: Date.now() });
}, 1000);
}
// Lifecycle: Called just before our component will be destroyed
componentWillUnmount() {
// stop when not renderable
clearInterval(this.timer);
}
render() {
let time = new Date(this.state.time).toLocaleTimeString();
return <span>{time}</span>;
}
}
into a "Functional Component" that uses Hooks as follows:
const ClockFn = () => {
const [time, setTime] = useState(Date.now());
useEffect(() => {
const timer = setInterval(() => {
setTime(Date.now());
console.log(Date.now());
}, 1000);
return () => {
clearInterval(timer);
console.log('unmount');
};
}, []);
return <span>{time}</span
><button
onClick={() => {
route('/');
}}
>
Go home
</button>;
};
the timer will continue to run. In the class component, on the other hand, the componentWillUnmount
lifecycle method is properly executed. If supporting this is outside of the scope of preact-router
please feel free to close.
Thanks in advance