React 筆記

React notes

Eddie Cheng
2 min readApr 19, 2021

更新換到我的 Github

Contents:

+ Components

+ JSX

+ Hooks

+ Higher-Order Components

+ React router

+ Redux

+ Other References

Components

The main building block for the applications is a Component.

Class components should always call the base constructor with props :

constructor(props) {
super(props);
this.state = {date: new Date()};
}

Two main patterns for sharing code

  1. Higher-order components
  2. Render props

state vs. props

  1. state is similar to props, but it is private and fully controlled by the component.

JSX

References

  1. Why does jsx require three dots in this code? (2017)

Hooks

Hooks are functions provided by react that lets you “hook” into React features from your “function components”

useState Hook

  • useState 讓我們可以在 function component 保留 local state
  • 每一次更新 state , React 就會 re-render function component

useEffect Hook

  • Runs a function every render of the components
  • The dependency array (a second argument of useEffect) => trigger for useEffect Hook
useEffect(() => {}, []); // with an empty dependency array, it runs function only once, after the first initial render
  • useEffect can return a function which is used to clean up (replace componentWillUnmount() in class component)

custom Hook

Just remember to name your custom Hook beginning with use (i.e. useWindowWidth, useXXXXXX)

useRef Hook

Very useful for persisting values across renders without actually causing a rerender.

Common use cases:

  1. To focus the element (i.e. <Input />)
  2. Store the previous state

References

  1. Learn useRef in 11 Minutes (2020.6)

Higher-Order Components

Concretely, a higher-order component is a function that takes a component and returns a new component.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

References

  1. Higher-Order Components

React router

  • Server responds html+js bundle
npm install react-router-dom

About <Redirect>

<Redirect> comes in handy in specific situations though, an example is when a 404 page is rendered when the user tries to access an undefined route. The <Redirect> will redirect the user from the 404 route to a new route of your choosing, and then replace the last entry in the history stack with the redirected route.

This means that the user will not be able to hit their browser’s back button, and return to the 404 route.

come in handy = to be useful

Some tips

  • It is better to always have <Switch><Switch/> surrounding the <Route>
  • Use <Link> to prevent the request to the server

References

[1] React-Router — Link vs Redirect vs History

Redux

  • A state management tool
  • Redux 經常與 React 搭配運用,但其也可以獨立使用

Other References

  1. React Today and Tomorrow and 90% Cleaner React With Hooks (2018)

--

--

Eddie Cheng

「0」が過去で「1」が未来「今」は何処にもない