React Tutorial for Java Delopers
Full Stack Development with Spring Boot 3 and React - Fourth Edition
이 책에서 React 관련 부분을 정리한 글
React
Create Project
Useful ES6 Features
Arrow functions
spread operator
{...user}
는 현재 user 상태의 복사본을 만듦이는 객체의 스프레드(spread) 연산자를 사용한 것으로, 기존 상태 객체의 모든 키와 값을 새 객체로 복사함
{...user, [event.target.name]: event.target.value}
구문기존 사용자 상태 객체의 복사본에 사용자가 방금 변경한 특정 필드 값을 업데이트함
Template literals
Object destructuring
Classes and inheritance
JSX and styling
JavaScript XML (JSX) is the syntax extension for JavaScript
Props and state
Props and state are the input data for rendering a component
The component is re-rendered when the props or state change.
Props
inputs to components
they are a mechanism to pass data from a parent component to its child component
Props are JavaScript objects, so they can contain multiple key-value pairs.
Props are immutable, so a component cannot change its props
Props are received from the parent component.
A component can access props through the props object that is passed to the function component as a parameter.
State
component state is an internal data store that holds information that can change over time
The state also affects the rendering of the component
When the state is updated, React schedules a re-render of the component
When the component re-renders, the state retains its latest values
State allows components to be dynamic and responsive to user interactions or other events.
The state is created using the useState hook function
const [state, setState] = React.useState(initialValue);
Stateless components
The React stateless component is just a pure JavaScript function that takes props as an argument and returns a React element.
function HeaderText(props) { return ( <h1> {props.text} </h1> ) } export default HeaderText;React provides React.memo(), which optimizes the performance of pure functional components.
import React, { memo } from 'react'; function HeaderText(props) { return ( <h1> {props.text} </h1> ) } export default memo(HeaderText);the component is rendered and memoized. In the next render, React renders a memoized result if the props are not changed.
Conditional rendering
React hooks
Hooks allow you to use state and some other React features in functional components
Before hooks, you had to write class components if states or complex component logic were needed
certain important rules for using hooks in React
You should always call hooks at the top level in your React function component
You shouldn’t call hooks inside loops, conditional statements, or nested functions
Hook names begin with the word use, followed by the purpose they serve.
useState
Batching
From React version 18 onward, all state updates will be batched. If you don’t want to use batch updates in some cases, you can use the react-dom library’s flushSync API to avoid batching.
useEffect
can be used to perform side effects in the React function component. The side effect can be, for example, a fetch request
useEffect(callback, [dependencies])
dependency
생략하면 각 렌더링 후에 useEffect콜백 함수가 호출
지정하면 해당 컴포넌트가 변경되었을 때만
빈 배열을 지정하면 컴포넌트가 처음 렌더링될 때만 호출
useRef
The useRef hook returns a mutable ref object that can be used, for example, to access DOM nodes
const ref = useRef(initialValue)
The ref object returned has a current property that is initialized with the argument passed (initialValue)
function App() { const inputRef = useRef(null); return ( <> <input ref={inputRef} /> <button onClick={() => inputRef.current.focus()}> Focus input </button> </> ); } export default App;we create a ref object called inputRef and initialize it to null
Then, we use the JSX element’s ref property and pass our ref object to it
Now, it contains our input element, and we can use the current property to execute the input element’s focus function
Now, when the button is pressed, the input element is focused:
Custom hooks
hooks’ names should start with the use word, and they are JavaScript functions.
The Context API
Handling lists with React
Handling events with React
you have to pass a function to the event handler instead of calling it
// Correct <button onClick={handleClick}>Press Me</button> // Wrong <button onClick={handleClick()}>Press Me</button>In React, you cannot return false from the event handler to prevent the default behavior.
Instead, you should call the event object’s preventDefault() method.
Handling forms with React
React Developer Tools Components tab
type something into the input field, we can see how the value of the state changes, and we can inspect the current value of both the props and the state.
TypeScript
union type
Using TypeScript features with React
State and props
name, age를 받는 prop을 인자로 받는 컴포넌트
FC(function component)
a standard React type
we can use with arrow functions.
This type takes a generic argument that specifies the prop type
const HelloComponent: React.FC<HelloProps> = ({ name, age }) => { return ( <> Hello {name}, you are {age} years old! </> ); };
Event
Rest Call
async and await
Using the fetch API
Using the Axios library
npm install axios
Using the React Query library
많이 사용되는 3ry party lib
React Query (https://tanstack.com/query), also known as Tanstack Query
SWR (https://swr.vercel.app/).
React Query provides the QueryClientProvider and QueryClient components, which handle data caching.
React Query provides the useQuery hook function, which is used to invoke network requests
queryKey is a unique key for a query and it is used for caching and refetching data
queryFn is a function to fetch data, and it should return a promise.
The query object that the useQuery hook returns contains important properties, such as the status of the query:
const { isLoading, isError, isSuccess } = useQuery({ queryKey: ['repositories'], queryFn: getRepositories })
isLoading: The data is not yet available.
isError: The query ended with an error.
isSuccess: The query ended successfully and query data is available.