Skip to content

Commit

Permalink
finish exercise 2
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds committed Mar 5, 2024
1 parent 8534ff3 commit e2e614e
Show file tree
Hide file tree
Showing 25 changed files with 1,560 additions and 5 deletions.
43 changes: 43 additions & 0 deletions exercises/01.managing-ui-state/05.problem.cb/README.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Init Callback

🦉 There's one more thing you should know about `useState` initialization and
that is a small performance optimization. `useState` can accept a function.

You may recall from earlier we mentioned that the first argument to `useState`
is only used during the initial render. It's not used on subsequent renders.
This is because the initial value is only used when the component is first
rendered. After that, the value is managed by React and you use the updater
function to update it.

But imagine a situation where calculating that initial value were
computationally expensive. It would be a waste to compute the initial value for
all but the initial render right? That's where the function form of `useState`
comes in.

Let's imagine we have a function that calculates the initial value and it's
computationally expensive:

```tsx
const [val, setVal] = useState(calculateInitialValue())
```

This will work just fine, but it's not ideal. The `calculateInitialValue` will
be called on every render, even though it's only needed for the initial render.
So instead of calling the function, we can just pass it:

```tsx
const [val, setVal] = useState(calculateInitialValue)
```

Typically doing this is unnecessary, but it's good to know about in case you
need it.

So

```tsx
// both of these work just fine:
const [query, setQuery] = useState(getQueryParam())
const [query, setQuery] = useState(getQueryParam)
```

You're going to be making the `getQueryParam` function. Got it? Great, let's go!
89 changes: 89 additions & 0 deletions exercises/01.managing-ui-state/05.problem.cb/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
html,
body {
margin: 0;
}

.app {
margin: 40px auto;
max-width: 1024px;
form {
text-align: center;
}
}

.post-list {
list-style: none;
padding: 0;
display: flex;
gap: 20px;
flex-wrap: wrap;
justify-content: center;
li {
position: relative;
border-radius: 0.5rem;
overflow: hidden;
border: 1px solid #ddd;
width: 320px;
transition: transform 0.2s ease-in-out;
a {
text-decoration: none;
color: unset;
}

&:hover,
&:has(*:focus),
&:has(*:active) {
transform: translate(0px, -6px);
}

.post-image {
display: block;
width: 100%;
height: 200px;
}

button {
position: absolute;
font-size: 1.5rem;
top: 20px;
right: 20px;
background: transparent;
border: none;
outline: none;
&:hover,
&:focus,
&:active {
animation: pulse 1.5s infinite;
}
}

a {
padding: 10px 10px;
display: flex;
gap: 8px;
flex-direction: column;
h2 {
margin: 0;
font-size: 1.5rem;
font-weight: bold;
}
p {
margin: 0;
font-size: 1rem;
color: #666;
}
}
}
}

@keyframes pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.3);
}
100% {
transform: scale(1);
}
}
103 changes: 103 additions & 0 deletions exercises/01.managing-ui-state/05.problem.cb/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { useState } from 'react'
import * as ReactDOM from 'react-dom/client'
import { generateGradient, getMatchingPosts } from '#shared/blog-posts'

// 🐨 make a function here called getQueryParam

function App() {
// 🐨 move 👇 up to getQueryParam
const params = new URLSearchParams(window.location.search)
const initialQuery = params.get('query') ?? ''
// 🐨 move 👆 up to getQueryParam and return the initialQuery

// 🐨 pass getQueryParam into useState
const [query, setQuery] = useState(initialQuery)
const words = query.split(' ')

const dogChecked = words.includes('dog')
const catChecked = words.includes('cat')
const caterpillarChecked = words.includes('caterpillar')

function handleCheck(tag: string, checked: boolean) {
const newWords = checked ? [...words, tag] : words.filter(w => w !== tag)
setQuery(newWords.filter(Boolean).join(' ').trim())
}

return (
<div className="app">
<form>
<div>
<label htmlFor="searchInput">Search:</label>
<input
id="searchInput"
name="query"
type="search"
value={query}
onChange={e => setQuery(e.currentTarget.value)}
/>
</div>
<div>
<label>
<input
type="checkbox"
checked={dogChecked}
onChange={e => handleCheck('dog', e.currentTarget.checked)}
/>{' '}
🐶 dog
</label>
<label>
<input
type="checkbox"
checked={catChecked}
onChange={e => handleCheck('cat', e.currentTarget.checked)}
/>{' '}
🐱 cat
</label>
<label>
<input
type="checkbox"
checked={caterpillarChecked}
onChange={e =>
handleCheck('caterpillar', e.currentTarget.checked)
}
/>{' '}
🐛 caterpillar
</label>
</div>
<button type="submit">Submit</button>
</form>
<MatchingPosts query={query} />
</div>
)
}

function MatchingPosts({ query }: { query: string }) {
const matchingPosts = getMatchingPosts(query)

return (
<ul className="post-list">
{matchingPosts.map(post => (
<li key={post.id}>
<div
className="post-image"
style={{ background: generateGradient(post.id) }}
/>
<a
href={post.id}
onClick={event => {
event.preventDefault()
alert(`Great! Let's go to ${post.id}!`)
}}
>
<h2>{post.title}</h2>
<p>{post.description}</p>
</a>
</li>
))}
</ul>
)
}

const rootEl = document.createElement('div')
document.body.append(rootEl)
ReactDOM.createRoot(rootEl).render(<App />)
4 changes: 4 additions & 0 deletions exercises/01.managing-ui-state/05.solution.cb/README.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Init Callback

👨‍💼 Great! This isn't 100% necessary as a performance optimization, but it's easy
and doesn't hurt readability so we may as well!
89 changes: 89 additions & 0 deletions exercises/01.managing-ui-state/05.solution.cb/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
html,
body {
margin: 0;
}

.app {
margin: 40px auto;
max-width: 1024px;
form {
text-align: center;
}
}

.post-list {
list-style: none;
padding: 0;
display: flex;
gap: 20px;
flex-wrap: wrap;
justify-content: center;
li {
position: relative;
border-radius: 0.5rem;
overflow: hidden;
border: 1px solid #ddd;
width: 320px;
transition: transform 0.2s ease-in-out;
a {
text-decoration: none;
color: unset;
}

&:hover,
&:has(*:focus),
&:has(*:active) {
transform: translate(0px, -6px);
}

.post-image {
display: block;
width: 100%;
height: 200px;
}

button {
position: absolute;
font-size: 1.5rem;
top: 20px;
right: 20px;
background: transparent;
border: none;
outline: none;
&:hover,
&:focus,
&:active {
animation: pulse 1.5s infinite;
}
}

a {
padding: 10px 10px;
display: flex;
gap: 8px;
flex-direction: column;
h2 {
margin: 0;
font-size: 1.5rem;
font-weight: bold;
}
p {
margin: 0;
font-size: 1rem;
color: #666;
}
}
}
}

@keyframes pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.3);
}
100% {
transform: scale(1);
}
}
Loading

0 comments on commit e2e614e

Please sign in to comment.