Skip to content

Commit

Permalink
properly memoize useEffect dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
ArchangelJTW committed Nov 30, 2023
1 parent e906271 commit f0fe9fe
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Calculator from './Calculator';
// Always keep injection point clean
function App() {
return (
<div className="App">
<div>
<Calculator />
</div>
);
Expand Down
24 changes: 11 additions & 13 deletions src/Calculator.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useCallback } from 'react';
import './Calculator.css';
import parseInput from './CalculatorParser';

function Calculator() {

const [input, setInput] = useState('');

const handleButtonClick = (value) => {
setInput(input + value);
};
const handleButtonClick = useCallback((value) => {
setInput((currentInput) => currentInput + value);
}, []);

const calculateResult = () => {
const calculateResult = useCallback(() => {
try {
const result = parseInput(input); // replaced `eval` it is considered unsafe and vulnerable to injection attacks
const result = parseInput(input);
if (result === null) {
throw new Error('Invalid expression');
}
Expand All @@ -21,13 +20,12 @@ function Calculator() {
setInput('Error');
console.log(error);
}
};
}, [input]);

const clearInput = () => {
const clearInput = useCallback(() => {
setInput('');
};
}, []);

// Handle keypresses
useEffect(() => {
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
Expand All @@ -38,7 +36,7 @@ function Calculator() {
handleButtonClick(event.key);
} else if (event.key === 'Backspace') {
event.preventDefault();
setInput(input.slice(0, -1));
setInput((currentInput) => currentInput.slice(0, -1));
}
};

Expand All @@ -47,7 +45,7 @@ function Calculator() {
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [input]);
}, [calculateResult, clearInput, handleButtonClick]);

// Build the user interface
return (
Expand Down

0 comments on commit f0fe9fe

Please sign in to comment.