import React, { useState, useEffect } from 'react';
function MyComponent(props) {
const [state, setState] = useState(initialState);
useEffect(() => {
// code to run after the component is mounted or updated
return () => {
// code to run before the component is unmounted
};
}, [dependency]);
function handleClick() {
// event handler for click events
}
return (
<div>
{/* JSX code goes here */}
</div>
);
}
export default MyComponent;
Use functions to make components in React. Can also use arrow functions to make function components.
function RandomNumber() {
//Logic that must happen before returning:
const n = Math.floor(Math.random() * 10 + 1);
//A return statement using that logic:
return <h1>{n}</h1>
}
To use JavaScript logic, you could put before the return statement which returns JSX.
import React, { useState, useEffect } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return (
<div>
<h2>Counter</h2>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
export default Counter;
Function components allow us to use hooks.
export default function Component(){
function handleClick() {
alert('Clicked!');
}
return <div onClick={handleClick}></div>;
}
Inline event handlers:
<button onClick={() => {
alert('Clicked!');
}}>
Make event handlers inside components before return statement and then pass it as props, don't use parentheses or it would call it immediately.