The Hooks are a functional component that simplify the use of React, and allow use to create some reusable component.
I have changed on my TodoList App a class to a Hooks
The React Class
class TodoListElementDelete extends React.Component {
constructor(props) {
super(props);
this.state = {
index: 0,
timer: 0,
_timeoutRef: null
};
this.onClickUndoDelete = this.onClickUndoDelete.bind(this);
}
componentDidMount() {
this.setState({
index: this.props.index,
timer: this.props.timer
});
}
componentDidUpdate() {
if (this.props.enable) {
this.state._timeoutRef = setTimeout(() => {
if (this.state.timer > 0) {
this.setState({
timer: this.state.timer - 1
});
} else {
this.props.onEndTimerAction();
}
}, 1000);
}
}
componentWillUnmount() {
console.log("componentWillUnmount");
clearTimeout(this.state._timeoutRef);
}
onClickUndoDelete() {
clearTimeout(this.state._timeoutRef);
this.setState({
timer: this.props.timer
});
this.props.onClickUndoDelete();
}
render() {
let classHideItem = this.props.enable ? "" : "hidden";
return (
<div className={"alert alert-danger " + classHideItem}>
You want to undo the action? {this.state.timer}
<button
type="button"
className="btn btn-warning"
onClick={this.onClickUndoDelete}
>
Undo
</button>
</div>
);
}
}
React Hooks
I have changed a React Class with React Hooks:
- timer managed with useState
- _timeoutRef with useRef
- ComponentDidMount, ComponentWillUnmount, ComponentDidUpdate with useEffect
const TodoListElementDelete = props => {
const [timer, setTimer] = React.useState(props.timer);
let _timeoutRef = React.useRef();
function onClickUndoDelete() {
clearTimeout(_timeoutRef.current);
setTimer(props.timer);
props.onClickUndoDelete();
}
React.useEffect(() => {
if (props.enable) {
_timeoutRef.current = setTimeout(() => {
if (timer > 0) {
setTimer(timer - 1);
} else {
props.onEndTimerAction();
}
}, 1000);
}
return () => clearTimeout(_timeoutRef.current);
});
return (
<div className={`alert alert-danger ${props.enable ? "" : "hidden"}`}>
You want to undo the action? {timer}
<button
type="button"
className="btn btn-warning"
onClick={onClickUndoDelete}
>
Undo
</button>
</div>
);
};
wow!