Maggie Appleton: Deepening the learning experience with meaningful visual metaphor design
case-study
Maggie is a cornerstone of egghead and our efforts. She might be best known for the superb course illustrations and illustrated notes.
Browse
Find courses, lessons, articles, talks, and podcasts.
7,176 resources
Showing 241–264 · Page 11 of 299
case-study
Maggie is a cornerstone of egghead and our efforts. She might be best known for the superb course illustrations and illustrated notes.
case-study
While earning his degree in Computer Science, Mahmoud found he really enjoyed creating content and started publishing it in a few different places.
case-study
Joe shares his story of sharing what he learns and how egghead supported him in his efforts.
case-study
case-study
Will is the community engineer at egghead. He energizes the community and makes connections, while also growing his career in tech
case-study
Instructor Case Study, more than a decade into a successful sales and business career, Shaundai found a passion for programming.
case-study
Instructor Case Study, Matías wanted to share his knowledge with others, while also leveling up his expertise.
case-study
Ceora is a digital marketer turned software engineer who enthusiastically and consistently engages with the development community.
article
If you've been working with React for a while, or you're a newbie, you will most likely attest to the fact that **Hooks** solve a wide variety of seemingly unconnected problems. Before the release of React hooks in 2019, the only way to "attach" reusable behavior to a component was through traditional patterns like render props and higher-order components. Using these patterns requires you to redesign your components which were, by all means, unmanageable and made code difficult to decipher, especially when building large applications. These issues led to the formation of hooks for sharing stateful logic. A component can change its state without changing its hierarchy, redesigning the component, or changing its structure. More so, this stateful logic can be extracted independently and reused across different components of your application. Hooks also let you use state and other React features without writing classes. In this article, we will be introducing React hooks from the ground up. We will start by looking at hooks from a high level - what are they, and why you should use them. I'll also take a look at the `useState`, and `useEffect` hooks. ## Prerequisites A basic knowledge of React is required to get the full value out of this article. <ArticleCourseCard course="the-beginner-s-guide-to-react"/> ## What is a hook? Hooks are functions that help you use state independently without writing a class. It is a new React feature that helps you write pure functional components without using the class syntax or this keyword. Additionally, we can leverage hooks to combine React concepts like props, state, context, refs, and lifecycle in our application. Hooks provide a more direct API to these concepts. It also lets us structure the logic inside a component into reusable entities. ## Motivation Behind Hooks Before the addition of hooks in React, developers encountered myriad problems ranging from difficulty reusing stateful logic between components to finding it hard to understand complex components. One of the motivations behind hooks is that they solve the problem of having to use layers of providers, consumers, higher-order components, render props, and other abstractions to reuse stateful logic between components in your application. Hooks gives us the liberty to have a logic that can stand alone in our component and repeatedly use without having to restructure your code. This invariably makes it easy to use hooks among many components in our application. Another motivation behind the addition of hooks is that they solve the problem of maintaining large, cumbersome applications. For example, a component might affect some data fetching in `componentDidMount` and `componentDidUpdate`. The `componentDidMount` method might also contain some varying logic that sets up event listeners. This is where the problem lies. Jointly related code gets split apart, while completely unrelated/varying code ends up joining in a single method, making it too cumbersome and easy to introduce bugs. How do hooks fix this issue, you may ask? Kindly follow along. Hooks allow you to divide a component into individual functions based on related pieces such as fetching data, rather than forcing a divide based on lifecycle methods (`componentDidMount`/`componentDidUpdate`). ## Using the State and Effect hooks in React Lets take a deep dive into these two hooks to fully understand them. I'll show you how you can effectively use both hooks with examples. Sounds interesting? Let's get started. We will be starting with the most important React hook- `**useState**`. To get started, let's create a new react application. In your terminal, run `npx create-react-app` to create all the boilerplate you need for your react application. Inside your `App.js` file, create an `App` functional component with a `-` and a `+` button with a `span` in the middle, which displays our count like so: ```js import React from 'react'; export default function App(){ return( <> <button>-</button> <span>0</span> <button>+</button> </> ) } ``` This is a simple react application with no functionalities at all, and we are going to be adding the counter functionalities by using the `useState` hook. To get started with implementing these functionalities, the first thing we'll need to do is import the hook we will use. Now, inside your `App.js`, at the top, import `useState` from React. Before we start, let me quickly iterate on the rules of hooks, one of which is that hooks can only be used inside of a function component. You cannot use them inside of a *class* component because classes have their way of doing the same things that hooks do. Another point to note about Hooks is that you cannot put hooks inside of conditional statements, functions, loops, and they cannot be nested in anything. They must be at the top level of your function, and nothing should be around them. Now that we know the rules let's talk about the `useState` hook and how it differs from the `class` state. ## useState To use the `useState` hook, all we need to do is just call the `useState`, which is a function. The thing that we pass into `useState` will be what our default state is, which in our example above is going to be `4`. `useState` always returns an array with two values. The first value will be your state, which In our example, will be `count`, and as a second value, we will use the `setCount` function to which we will use to update our state. Let's update our application. In between your span element, replace the `0` with `{count}` so it can be rendered. Your App.js file should look like this: ```js import React, { useState } from 'react'; export default function App(){ const [ count, setCount] = useState(4); return( <> <button>-</button> <span>{count}</span> <button>+</button> </> ) } ``` The next thing I want to talk about is how we can actually `setCount`. To do that, lets set an `onClick` called `decrementCount` inside our `-` button. Following that, let’s define a function called `decrementCount` like so: ```js function decrementCount(){ setCount(preCount => preCount - 1) } ``` Let’s also apply same functionality inside our `+` button like so: ```js function incrementCount(){ setCount(preCount => preCount + 1) } ``` Run `npm start` and click on both buttons to see how well they perform. Awesome right? These are the basic functionalities of the `useState` hook. Your `App.js` file should look like this: ```js import React, { useState } from 'react'; export default function App(){ const [ count, setCount] = useState(4); function decrementCount(){ setCount(preCount => preCount - 1) } function incrementCount(){ setCount(preCount => preCount + 1) } return( <> <button onClick={decrementCount}>-</button> <span>{count}</span> <button onClick={incrementCount}>+</button> </> ) } ``` ## useEffect Lastly, let's talk about the **useEffect** hook. Two things you should note about the `useEffect` hook. Firstly, it lets you perform side effect in functional component and secondly, the `useEffect` hook is synonymous in function to `componentDidMount`, `componentDidUpdate` and `componentWillUnmount`. First things first, to make use of the `useEffect` hook, you have to import it from React and call it at the top of your page, similar to the `useState`. Let's begin: In your editor, type the following piece of code. ```js import { useEffect } from "react"; function App(){ return( <div className="App">Learning useEffect</div> ) } ``` From the above, we rendered “Learning useEffect” on our code and when it is rendered, the `useEffect` hook will be called. Add a `useEffect` Inside of our function `App` like so: ```js import { useEffect, useState } from "react"; function App(){ const [counter, setCounter] = useState(0); useEffect(() =>{ }) return( <div className="App">useEffect</div> ) } ``` Inside the parenthesis, we can pass a function, which can be whatever logic we want in our code. However, it is important to understand that the `useEffect` will get called after our page is rendered. From our code above, whenever our `state` changes, the `useEffect` will be called. The `state` has a default value of `0`, and whenever the default value changes, `useEffect` will be re-rendered. For example, in our application, let's console.log `counter` and add a `button` with an `onClick` function to increase our counter value by `1` whenever the button gets clicked. ```js import { useEffect, useState } from "react"; function App(){ const [counter, setCounter] = useState(0); useEffect(() =>{ console.log(counter) }) return( <div className="App"> {counter} <button onClick={() =>{ setCounter(counter + 1) }}>Increase</button> </div> ) } ``` ## **Rules of Hooks** - **Call hooks at the top level**: As a rule of thumb in React, hooks should only get called at the top level of your React application before any early returns. It must not get called inside loops, conditions, or nested ****functions. - Hooks must be called from React functions components or custom hooks only, not JavaScript functions If some things didn't quite make a lot of sense to you, check out the [hooks API reference] (https://reactjs.org/docs/hooks-reference.html), or https://reactjs.org/docs/hooks-faq.html
article
Sometimes when building React applications, we want to share logic between JavaScript functions. To do this as a developer, we extract the particular logic and put it in a function, right? These functions in React are what we call **Custom Hooks.** Custom hooks are functions that we create to make logic accessible to other components or functions in an application. As with other hooks in React, a custom hook must: - Be called at the very top level of your React function to ensure that hooks are called in the same order each time a component renders. - Start with the `use` keyword - Never be called inside a nested function, a loop, or condition - Only be called from functional components in React ## Prerequisites A basic knowledge of React and React hooks is required to get the full value out of this article. <ArticleCourseCard course="the-beginner-s-guide-to-react"/> ## Building Your First Custom Hooks To demonstrate how to create a custom hook, I will divide this lesson into two parts. In the first half, we will write code without any custom hooks, and in the second part, we will move some logic into a custom hook. Are you excited? Let's get started. For this example, we will implement **a simple form where a user can submit their first and last name**. To begin, let's create a new React app by running `npx create-react-app custom-hooks`. After creating your react app, create a `components` folder inside your `src` folder. Inside your `components` folder, create a `UserForm.js` file. Your folder structure should look like this:  Now, inside your `UserForm.js` file create a functional component. We need two state variables for our `firstName` and `lastName`(remember we want to create a submit form where users can submit their first and last names), so we are going to import the `useState` hook in react at the top of our file and create the two variables. Next, let's add the jsx. Inside your `return` statement, add a `form` tag that will contain some `input` elements for our first and last name. Now your `UserForm.js` file should look like this: ```js import React from 'react'; import { useState } from 'react'; export default function UserForm() { const [firstName, setfirstName] = useState(''); const [lastName, setlastName] = useState(''); return( <> <form> <div> <label>First Name</label> <input type='text' /> </div> <div> <label>Last Name</label> <input type='text' /> </div> <button>Submit</button> </form> </> ) } ``` The next step is to convert these `input` elements into a controlled component like so: ```js import React from 'react'; import { useState } from 'react'; export default function UserForm() { const [firstName, setfirstName] = useState(''); const [lastName, setlastName] = useState(''); return( <> <form> <div> <label>First Name</label> <input value={firstName} onChange={e =>setfirstName(e.target.value)} type='text' /> </div> <div> <label>Last Name</label> <input value={lastName} onChange={e =>setlastName(e.target.value)} type='text' /> </div> <button>Submit</button> </form> </> ) } ``` Noticed from the above, we added `value` and `onChange` attributes (where `e` in `onChange` stands for “**event**”), to our input elements to make them interactive. Next, we are going to add a `submitHandler` to our `form` tag and create the `submitHandler` function. Inside our `submitHandler` function, let’s add the `e.preventdefault()` method to stop the code from refreshing and an alert method which we will use to display our input names like so: ```js const submitHandler = e => { e.preventDefault(); alert(`Hello ${firstName} ${lastName}`) } ``` We are almost done with the first part of our code. Your `UserForm` function should look like this: ```js const [firstName, setfirstName] = useState(''); const [lastName, setlastName] = useState(''); const submitHandler = e => { e.preventDefault(); alert(`Hello ${firstName} ${lastName}`); } return( <> <form onSubmit={submitHandler}> <div> <label>First Name</label> <input value={firstName} onChange={e =>setfirstName(e.target.value)} type='text' /> </div> <div> <label>Last Name</label> <input value={lastName} onChange={e =>setlastName(e.target.value)} type='text' /> </div> <button>Submit</button> </form> </> ) ``` One last thing before we finish the first part of our code. Let's go to our `App.js` file, remove the boilerplate code, import our `UserForm` component, and return it like so: ```js import React from 'react'; import UserForm from './components/UserForm'; function App() { return ( <div> <UserForm /> </div> ); } export default App; ``` Next, go to your terminal, inside your project directory, and run `npm start`. You should get redirected to your browser. Add a first and last name inside the input fields and submit. Notice the `alert` method returned your inputs prefixed by the "Hello" word we added? Pretty straightforward, yeah? Now, let's create our custom hook. For this example, we want our custom hook to encapsulate controlled component behavior for our input element. In other words, we want to be able to bind the `value` and `onChange` attributes together since they are repeated severally in our `UserForm.js` file. Let's see how: - Create a new folder called `hooks` inside of your `src` folder - Inside your hooks folder, create a file called `useInput.js`. In our `useInput` custom hook, we want to create a logic that can track our input fields' value. To implement this logic, we would need to import `useState` from React and set our `useState` to a variable with a parameter of `initialValue` like so: ```js import { useState } from 'react'; export default function useInput(initialValue){ const [value, setValue] = useState(initialValue); } ``` Now that we have the value and a function to update the value- `setValue`, let's add our logic. First, let's create an object called `reset` that allows us to set the `value` back to the initial value (`initialValue`) and an object called `bind` with two properties. The first property is `value`, and the second property is `onChange`. The `onChange` property is going to be a function that receives the event as a parameter and sets the value to `e.target.value` Finally, we will return three things; the `value`, `bind`, and `reset` like so: ```js import { useState } from 'react'; export default function useInput(initialValue){ const [value, setValue] = useState(initialValue); const reset = () => { setValue(initialValue); } const bind = { value, onChange: e => { e.target.value } }; return [value, bind, reset]; } ``` Next, let's see how to incorporate this logic in our component. In your `useForm.js` file, import the `useInput` file on the top of your page. After that, just underneath your `UserForm` function, write the following lines of code to replace the `useState` call for the `firstName`. ```js const [firstName, bindFirstName, resetFirstName] = useInput(''); const [lastName, bindLastName, resetLastName] = useInput('') ``` Remember that a call to `useInput` in our `useInput` file returns three values (firstName, bindFirstName, resetFirstName). Here in our `UserForm` file, we destructured all three and deleted our `useState` call for both `firstName` and `lastName`. Noticed that `firstName` and `lastName` has already been used in the `submitHandler` function. Now, to use the `bindFirstName`, `bindLastName`, `resetFirstName` and `resetLastName`, we would need to replace the `value` and `onChange` attributes for `firstName` while `bindLastName` would need to replace the `value` and `onChange` attributes for `lastName` in our form. This is possible because the code is in fact one and the same. Something like this: ```js <form onSubmit={submitHandler}> <div> <label>First Name</label> <input {...bindFirstName} type='text' /> </div> <div> <label>Last Name</label> <input {...bindLastName} type='text' /> </div> <button>Submit</button> </form> ``` One last thing before we round up with this. For the reset functions, we can make use of them in the `submitHandler` like so: ```js const submitHandler = e => { e.preventDefault(); alert(`Hello ${firstName} ${lastName}`); resetFirstName(); resetLastName(); } ``` In the end, your `userForm` file should look like this: ```js import React from 'react'; import { useState } from 'react'; import useInput from '../hooks/useInput'; export default function UserForm() { const [firstName, bindFirstName, resetFirstName] = useInput(''); const [lastName, bindLastName, resetLastName] = useInput('') const submitHandler = e => { e.preventDefault(); alert(`Hello ${firstName} ${lastName}`); resetFirstName(); resetLastName(); } return( <> <form onSubmit={submitHandler}> <div> <label>First Name</label> <input {...bindFirstName} type='text' /> </div> <div> <label>Last Name</label> <input {...bindLastName} type='text' /> </div> <button>Submit</button> </form> </> ) } ``` That's pretty much it. You can save the file and take a look at your browser. Noticed after you try inputting, the form refreshes itself (courtesy of the reset button), showing us that our `useInput` custom hook works as expected. You can find the complete code here in my GitHub repository- https://github.com/QNNAKWUE/custom-hooks.
course
This course is perfect for those looking for a lightweight alternative to NgRx Store that scales effortlessly.
course
Dive into the world of real-time web development with this hands-on course! You’ll learn how to build a dynamic chat application using Fauna Streams and Next.js 14, focusing on the essentials and best practices. **What You’ll Learn:** - **Next.js Best Practices:** Master Next.js best practices for building fast, maintainable apps. - **Server-Side Rendering (SSR):** Learn SSR techniques and master features like server actions, server side form submission etc. - **Database Access Patterns:** Efficiently connect and retrieve data using Fauna. - **Real-Time Updates:** Implement real-time updates with Fauna Streams. - **Basic Authentication:** Secure your chat app with simple authentication methods. **Course Highlights:** - Practical, project-based learning. - Clear, step-by-step instructions. - Focus on modern, real-time web development. - Tips and tricks for optimizing performance. By the end of this course, you’ll have a working real-time chat app and a solid grasp of the tools and techniques used to build it.
lessonDuration 24sFree
Our app is in a good stopping point. A good challenge for you to implement from here is to implement a navbar with a `logout` button.
lessonDuration 2m 15sFree
Now that we have user information available to us, we want to connect messages created to the users that are sending them. When we add `read` privileges to the `User` model, we can call `User.identity()` to get the user data we need to set for messages.
lessonDuration 3m 23sFree
Now that we have user Authentication, we can redirect users to sign in if we don't find a cookie to do so. Throughout our app we can now replace our fauna token we have set in environment variables to the user token that we have access to.
lessonDuration 4m 12sFree
For user signin, we'll implement a proper server action by creating a `actions.js` file where our server actions can live. In our login page, we'll set the component to be a client component to hold some state. This way we can use the new `useFormState` hook from `react-dom` and pass in our login server action. Within the action we'll call our `UserLogin` function from Fauna and set a cookie with the secret we get back that we can use throughout our application.
lessonDuration 2m 43sFree
Now it's time to actually sign users up for our appliaction. We'll implement the `doSignup` function that we created earlier. This function will run on the server with the `'use server'` directive so we can instantiate a fauna client and call `UserRegistration` within this function. From there we'll redirect the user to the `/signin` page which will error out because it's not implemented yet.
lessonDuration 7m 30sFree
To have actual users in our application we need to represent those users in our database. Fauna has quite a few ways you can do user authentication but we'll be creating our own using a few built-in Fauna helpers. We'll start by setting up the necessary Fauna logic for users. We'll add a `User` collection as well as a `functions.fsl` file that we'll expose user sign up and log in. Here we'll see how Fauna gives us a built in `Credentials` document to handle email and password for a user. It also has a login function that it exposes to make that easy for us which will generate a token for a user on login. After setting up our functions, we'll add an `UnAuthRole` as well as an `AuthRole` and give proper actions for each role.
lessonDuration 7m 33sFree
To take advantage of Next.js app router, we need to separate our client components that need state from the rest of the page so we can load data on the server. To do this we'll refactor the list of rooms into it's own `RoomList` component which will take the client-side React hooks with it. This way we can load all our rooms on the server and just pass it to `RoomList` which will start to stream the rooms as we create them. The final step will be to turn the form for creating rooms into a server action. You'll notice that we will need to instantiate a new fauna client within the server action even though we have a client available in that same page.
lessonDuration 1m 8sFree
You'll notice that at the top level, we've set `'use client'` for our page. This means that everything on the page is a client component and we miss out on some benefits Next.js gives us by rendering on the server which includes a smaller bundle where sending to the client. We'll fix this in the next lesson.
lessonDuration 6m 24sFree
To stream messages, we'll implement logic very similar to how we stream the creation of rooms from earlier. First, we need to convert `MessageList` into a client component. We'll get an interesting error saying that only plain objects can be passed to client components from server components. This happens because the response we get back from Fauna is pretty complex. To fix this error we'll create a simple messages array and pass that down to the `MessageList` component. In the `MessageList` component we'll create a `useEffect` that will initiate a Fauna stream within a ref and push new messages into state that we are holding in the component.
lessonDuration 6m 24sFree
Now it's time to actually create messages and display them in rooms within our application. We'll start by creating a `MessageForm` component that will send a `Message.create` query to Fauna on form submission. Next, we'll display these messages by updating our room query to also get all the messages for that room. You'll see that we can still just perform one query because we pass in the room id and call `Message.where(.room == room)` to the query. One note here is if you console log your messages in your page component, you'll notice that the logs show up in the terminal and not the browser. This is because we are using a server component.
lessonDuration 4m 21sFree
We'll take a moment to explore how Fauna handles one-to-many relationships inside the fauna shell. First we'll create a `Message` collection. Then we'll connect to the cloud database by running `fauna shell`, because I'm logged and configured this connects to the database I'm working with. In the terminal we'll see how to create multiple messages that are associated with a room and query for those messages by room.
lessonDuration 4m 3sFree
With rooms being created and displayed on the index page, it's now time to create dynamic routes for each room so that when you click on a room name, you are actually navigated to that room. We'll do this by using Next.js dynamic route syntax `/rooms/[...id]/page.js`. This will render a page on any `/rooms/:id` passing the component we define the `:id` as params. Here we'll take that id and fetch the room data from fauna with a `Room.byId` query.