
import React, { useEffect, useState } from "react";
import Button from "../components/Button";
export default function CounterPage({ initialCount }) {
const [count, setCount] = useState(initialCount);
useEffect(() => {
console.log(count);
}, [count]);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<h1>Count is {count}</h1>
<Button onClick={handleClick}>Increment</Button>
</div>
);
}
<Route path="/counter">
<CounterPage initialCount={10} />
</Route>
Inside the CounterPage.js
We have [count, useEffect, handleClick, JSX ]
count, useEffect, handleClick =>
Three chunks of code that
1. Creates number state based on an initial value
2. Logs that value any time it changes
3. Provides a way to change that value
Extract those threee chunks and make a reusable hook
This will get you pretty far
1. Find code in a component related to a single piece of state
2. Copy paste it all into a helper function
3. Fix all the broken references
4. you have a hook
useCounter()
[count, useEffect, handleClick]
function useSomething(){}
Find all the non-JSX expressions that refer to 1-2 related pieces of state
Cut them all out, paste them into 'useSomething'
function useSomething() {
const [count, setCount] = useState(initialCount);
useEffect(() => {
console.log(count);
}, [count]);
const handleClick = () => {
setCount(count + 1);
};
}
4.Find 'not definded' errors in your component
=> count, handleClick
5. In your hook, return an object that contains the variables that component needs.
function useSomething() {
....
return {
count,
handleClick,
};
}
const {count, handleClick} = useSomething()
function useSomething(initialCount) {
const [count, setCount] = useState(initialCount);
...
}
export default function CounterPage({ initialCount }) {
const { count, handleClick } = useSomething(initialCount);
return (
<div>
<h1>Count is {count}</h1>
<Button onClick={handleClick}>Increment</Button>
</div>
);
}
export default function CounterPage({ initialCount }) {
function useCounter(initialCount) {
const [count, setCount] = useState(initialCount);
useEffect(() => {
console.log(count);
}, [count]);
const increment = () => {
setCount(count + 1);
};
return {
count,
increment,
};
}
const { count, increment } = useCounter(initialCount);
return (
<div>
<h1>Count is {count}</h1>
<Button onClick={increment}>Increment</Button>
</div>
);
}