6.2 week React, axios, paging, useMemo, memo, react-core-concept, consom-hooks
//side effect*
//side effect in React, the concept of side effects encompasses any operations that reach outside the functional scope of a React component. These operations can affect other components, interact with the browser, or perform asynchronous data fetching.
//useState is a React Hook that lets you add a state variable to your component. const [state, setState] = useState(initialState) useState(initialState) set functions, like setSomething(nextState)
//UseEffect**
import { useEffect, useState } from 'react'
import './App.css'
import axios from "axios";
function App() {
const [todos, setTodos] = useState([]);
useEffect(() => {
axios.get("https://sum-server.100xdevs.com/todos")
.then(function (response) {
setTodos(response.data.todos)
})
}, []);
return (
<>
{todos.map(todo => <Todo key={todo.id} title={todo.title} description={todo.description} />)}
</>
)
}
function Todo({title, description}) {
return (<>
<h1> {title} </h1>
<p>{description}</p>
</>
)
}
export default App
import './App.css'
import axios from "axios";
function App() {
const [todos, setTodos] = useState([]);
useEffect(() => {
axios.get("https://sum-server.100xdevs.com/todos")
.then(function (response) {
setTodos(response.data.todos)
})
}, []);
return (
<>
{todos.map(todo => <Todo key={todo.id} title={todo.title} description={todo.description} />)}
</>
)
}
function Todo({title, description}) {
return (<>
<h1> {title} </h1>
<p>{description}</p>
</>
)
}
export default App
//axios is minimal way to fetch the data from server rather than using fetch and and async await method
// write a component that takes a todo id as an input fetches the data for that todo from the given endpoint And then renders it
import { useEffect, useState } from 'react'
import './App.css'
import axios from "axios";
function App() {
return(
<>
<Todo id={5} />
</>
)
}
function Todo({id}) {
const [todo, setTodos] = useState([]);
// use effect your code
useEffect(() => {
axios.get("https://sum-server.100xdevs.com/todo?id=" + id)
.then(function (response) {
setTodos(response.data.todo)
})
}, []);
return (<>
<h1> {todo.title} </h1>
<p>{todo.description}</p>
</>
)
}
export default App
import { useEffect, useState } from 'react'
import './App.css'
import axios from "axios";
function App() {
return(
<>
<Todo id={5} />
</>
)
}
function Todo({id}) {
const [todo, setTodos] = useState([]);
// use effect your code
useEffect(() => {
axios.get("https://sum-server.100xdevs.com/todo?id=" + id)
.then(function (response) {
setTodos(response.data.todo)
})
}, []);
return (<>
<h1> {todo.title} </h1>
<p>{todo.description}</p>
</>
)
}
export default App
//paging*
// write a component that take id as button of page clicking on button todo responses will change your page is an input fetches the data for that todo from the given endpoint And then renders it
import { useEffect, useState } from 'react'
import './App.css'
import axios from "axios";
function App() {
const [selectedId, setSelectedId] = useState(1);
return (
<>
<button onClick={function () {
setSelectedId(1)
}} >1</button>
<button onClick={function () {
setSelectedId(2)
}} >2</button>
<button onClick={function () {
setSelectedId(3)
}} >3</button>
<button onClick={function () {
setSelectedId(4)
}} >4</button>
<button onClick={function () {
setSelectedId(5)
}} >5</button>
<Todo id={selectedId} />
</>
)
}
function Todo({ id }) {
const [todo, setTodos] = useState({});
// use effect your code
useEffect(() => {
axios.get("https://sum-server.100xdevs.com/todo?id=" + id)
.then(function (response) {
setTodos(response.data.todo)
})
}, [id]);
return (<>
id: {id}
<h1> {todo.title} </h1>
<p>{todo.description}</p>
</>
)
}
export default App
//memo
//memoize the value across re-renders, only recalculate it if inputVal changes
//ugly way*
//write a code to calculae the number of 1 to n
//here we use memo to avoid run function to calculate that in the past
import { useEffect, useState } from 'react'
import './App.css'
import axios from "axios";
// useMemo
import { useEffect, useMemo, useState } from 'react'
import './App.css'
import axios from "axios";
// useMemo
function App() {
const [counter, setCounter] = useState(0);
const [inputValue, setInputValue] = useState(1);
let count = useMemo(() => {
console.log("memo got called");
let finalCount = 0;
for (let i =1; i<= inputValue; i++) {
finalCount = finalCount + i;
}
return finalCount;
}, [inputValue]);
return<div>
<input onChange={function (e) {
setInputValue(e.target.value);
}} placeholder={"Find the sum of 1 to n"}></input>
<br />
Sum from 1 to {inputValue} is {count}
<br />
<button onClick={() => { setCounter(counter + 1);}}> counter ({counter}) </button>
</div>
}
export default App
---------------------------------------------------------------------------------------------------------------------------------
import { useEffect, useState } from 'react'
import './App.css'
import axios from "axios";
// useMemo
import { useEffect, useMemo, useState } from 'react'
import './App.css'
import axios from "axios";
// useMemo
function App() {
const [counter, setCounter] = useState(0);
const [inputValue, setInputValue] = useState(1);
let count = useMemo(() => {
console.log("memo got called");
let finalCount = 0;
for (let i =1; i<= inputValue; i++) {
finalCount = finalCount + i;
}
return finalCount;
}, [inputValue]);
return<div>
<input onChange={function (e) {
setInputValue(e.target.value);
}} placeholder={"Find the sum of 1 to n"}></input>
<br />
Sum from 1 to {inputValue} is {count}
<br />
<button onClick={() => { setCounter(counter + 1);}}> counter ({counter}) </button>
</div>
}
export default App
---------------------------------------------------------------------------------------------------------------------------------
//useCallback*
"useCallback" is a hooke in react, a popular JavaScript library for building user interfases. it is ued to memorise function which can hellp in optimizing the performances of your applications, especially in case involving child components that rely on reference equality to prove unnecessary renders
"useCallback" is a hooke in react, a popular JavaScript library for building user interfases. it is ued to memorise function which can hellp in optimizing the performances of your applications, especially in case involving child components that rely on reference equality to prove unnecessary renders
//when you update child it is updated/reader but when you update parent then child also re-renders itself if you wrap the child inside the memo then it doesn't reader itself when parent getting updated.
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import './App.css'
import axios from "axios";
var a = 1;
// useMemo
function App() {
const [counter, setCounter] = useState(0);
// const [inputValue, setInputValue] = useState(1);
const a = useCallback(function(){
console.log("Hi There man");
}, [])
return (<>
<button onClick={() => {
setCounter(counter + 1);
}}>Counter({counter})</button>
<Demo a={a} />
</>)
}
let Demo = memo(function({a}) {
console.log("rerender");
return<div>
Hi here
</div>;
});
export default App
----------------------------------------------------------------------------------------------------------------------------
react core concepts
Absolutely! React can have some unique syntax that might take time to get used to. Let's break down the key parts and make them more approachable.
**Core Concepts**
1. **JSX:** JSX might look like HTML, but it's actually an extension of JavaScript. It allows you to write what looks like HTML structures within your JavaScript code. This gets transpiled into regular JavaScript that the browser understands.
Example:
```jsx
const element = <h1>Hello, world!</h1>;
```
2. **Components:** Components are the building blocks of React applications. There are two main types:
* **Functional Components:** These are simple JavaScript functions that return JSX to describe what should be rendered.
```javascript
const MyComponent = () => {
return <div>Hello from MyComponent</div>;
};
```
* **Class Components:** These are traditional classes (using the `class` keyword) that have more features, such as the ability to manage their own state. They are used less often these days in favor of functional components with hooks.
3. **Props:** Props are like arguments passed to components. They allow you to send data from parent components down to child components, making them customizable.
```javascript
<MyComponent name="Alice" />
```
4. **State:** React components can have internal state, which is data that can change within the component over time. This state can trigger re-renders when updated, causing the UI to reflect the changes. React's `useState` hook is the common way to manage state.
```javascript
const [count, setCount] = useState(0);
```
**Common Syntax Patterns**
* **Component Usage:**
```jsx
<MyComponent prop1="value1" prop2={someVariable} />
```
* **Event Listeners:**
```jsx
<button onClick={handleClick}>Click Me</button>
```
* **Conditional Rendering:**
```jsx
{showContent && <p>This content is only shown if showContent is true</p>}
```
* **Lists and Iteration:**
```jsx
const items = [1, 2, 3];
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
```
**Tips for Understanding**
* **Start Simple:** Begin with small components and gradually build more complex structures.
* **Learn by Doing:** Create small projects and experiment. Hands-on coding is the best way to cement the concepts.
* **React DevTools:** The React Developer Tools browser extension lets you inspect your components' hierarchy, props, and state right in the browser.
* **Documentation:** The official React documentation ([https://reactjs.org/](https://reactjs.org/)) is excellent.
**Would you like me to focus on any specific syntax pattern that you find particularly tricky? I'm here to help!**
**Core Concepts**
1. **JSX:** JSX might look like HTML, but it's actually an extension of JavaScript. It allows you to write what looks like HTML structures within your JavaScript code. This gets transpiled into regular JavaScript that the browser understands.
Example:
```jsx
const element = <h1>Hello, world!</h1>;
```
2. **Components:** Components are the building blocks of React applications. There are two main types:
* **Functional Components:** These are simple JavaScript functions that return JSX to describe what should be rendered.
```javascript
const MyComponent = () => {
return <div>Hello from MyComponent</div>;
};
```
* **Class Components:** These are traditional classes (using the `class` keyword) that have more features, such as the ability to manage their own state. They are used less often these days in favor of functional components with hooks.
3. **Props:** Props are like arguments passed to components. They allow you to send data from parent components down to child components, making them customizable.
```javascript
<MyComponent name="Alice" />
```
4. **State:** React components can have internal state, which is data that can change within the component over time. This state can trigger re-renders when updated, causing the UI to reflect the changes. React's `useState` hook is the common way to manage state.
```javascript
const [count, setCount] = useState(0);
```
**Common Syntax Patterns**
* **Component Usage:**
```jsx
<MyComponent prop1="value1" prop2={someVariable} />
```
* **Event Listeners:**
```jsx
<button onClick={handleClick}>Click Me</button>
```
* **Conditional Rendering:**
```jsx
{showContent && <p>This content is only shown if showContent is true</p>}
```
* **Lists and Iteration:**
```jsx
const items = [1, 2, 3];
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
```
**Tips for Understanding**
* **Start Simple:** Begin with small components and gradually build more complex structures.
* **Learn by Doing:** Create small projects and experiment. Hands-on coding is the best way to cement the concepts.
* **React DevTools:** The React Developer Tools browser extension lets you inspect your components' hierarchy, props, and state right in the browser.
* **Documentation:** The official React documentation ([https://reactjs.org/](https://reactjs.org/)) is excellent.
**Would you like me to focus on any specific syntax pattern that you find particularly tricky? I'm here to help!**
--------------------------------------------------------------------------------------------------------------------
//costom hooks
// costom hooks is like useState, useEffect, you can write your own hooks there is only one condition is it should start with a use(naming convention)
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import './App.css'
import axios from "axios";
// var a = 1;
// useMemo
function App() {
const [count, setCounter] = useState(0);
function logSomthing() {
console.log("child clicked");
}
return (<>
<ButtonComponent inputFunction= {logSomthing} />
<button onClick={() => {
setCounter(count + 1);
}}>Click me({count})</button>
</>)
}
const ButtonComponent = memo(({inputFunction}) => {
console.log("Child render")
return<div>
<button onClick={inputFunction}>Button Clicked</button>
</div>
})
export default App
---------------------------------------------------------------------------------------------------------------------------
// 27030O8C3103241200011
Comments