W3Schools Tryit Editor

[フレーム]
Get your own React server
main.jsx
index.html
//With useCallback:
import React, { useState, useCallback } from 'react';
import { createRoot } from 'react-dom/client';
// Child component that receives a function prop
const Button = React.memo(({ onClick, text }) => {
 console.log(`${text} button rendered`);
 return <button onClick={onClick}>{text}</button>;
});
// Parent component with useCallback
function WithCallbackExample() {
 const [count1, setCount1] = useState(0);
 const [count2, setCount2] = useState(0);
 // These functions are memoized and only recreated when dependencies change
 const handleClick1 = useCallback(() => {
 setCount1(count1 + 1);
 }, [count1]);
 const handleClick2 = useCallback(() => {
 setCount2(count2 + 1);
 }, [count2]);
 console.log("Parent rendered");
 return (
 <div>
 <h2>With useCallback:</h2>
 <p>Count 1: {count1}</p>
 <p>Count 2: {count2}</p>
 <Button onClick={handleClick1} text="Button 1" />
 <Button onClick={handleClick2} text="Button 2" />
 </div>
 );
}
createRoot(document.getElementById('root')).render(
 <WithCallbackExample />
); 
 
<!doctype html>
<html lang="en">
 <body>
 <div id="root"></div>
 <script type="module" src="/src/main.jsx"></script>
 </body>
</html>
 
localhost:5173

AltStyle によって変換されたページ (->オリジナル) /