본문 바로가기
카테고리 없음

Learning React Essentials 5

by 부엉이의 정보 창고 2022. 1. 25.
728x90

React with Redux

Connecting React with Redux is done like below.

    1. Creates a React component
    1. Creates a Redux store
    1. Connect the component with the store using react-redux package
  • React : Javascript view library
  • Redux : State management framework. developed by React developers
  • Redux => creates a single Redux store, managing application state
  • React => subscribes to some of the store's data. If action dispatched, the React component gets updated
  • When application gets bigger and complicated, using Redux is recommended
  • Use react-redux package and pass Redux state/dispatch to React as props

Provider

Provider is essential for React-Redux app. Provider is a wrapper component wrapping React app, accessing Redux store.

<Provider store={store} > 
    <App/> 
</Provider>

Connect

Connect is a method that connects React component with Redux, taking two optional arguments like below. It allows you to provide state and dispatch. Clarify what state and action you need so that component only approaches to the state it needs.

connect(mapStateToProps, mapDispatchToProps)(MyComponent) // replace argument with null if needed
  • mapStateToProps : provide a specific state to Redux store
  • mapDispatchToProps : provide a specific action creator to dispatch action against Redux store

State and dispatch passed by mapStateToProps and mapDispatchToProps can be accessed as props in the MyComponent.

React Hooks

Hooks are added in React 16.08. Hooks API are useful to

  • make stateless components with function
  • do easier state management without Redux/Mobx

Hooks do not work inside class, meaning hook and class is incompatiable. You either use hook or class.

 

Before the hook is introduced, if you want to add some state but you were working on function component, you had to re-write class component to add the state. Once hook is introduced, adding state in functional component becomes available. Hook names always start with "use" and embraces clousure in Javascript.

Types of Hooks

  • useState(initial state) : declare a state variable with initial state. Returns a current state and a function to update.
  • useEffect(effect function)
  • useContext
  • useReducer
  • useCallback .. and many more

useState and useEffect

useState

Let's see how useState hook is defined in React offical homepage.

~ useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React. ... React will remember its current value between re-renders, and provide the most recent one to our function.
// class component with 'this' : A 
class MyComonent extends React.Component { 
    constructor(props) { 
        super(props)
        this.state = { 
            count : 0
        }
    }
}

// function component with 'hook' : B 
import { useState, useEffect } from "react"
const MyComponent = () => {
    const [count, setCount] = useState(0) // declare a state variable. 
}

// Component A and B is the same. 

useEffect

useEffect lets you perform side effects(listed below) in function components. By default, it runs both after the first render and after every update. It is similar to componentDidMount and componentDidUpdate.

React updates DOM => React calls useEffect
  • data fetching or other API
  • setting up a subscription
  • changing DOM

By using useEffect hook, your components will do something else additionally after render. Every time we re-render, we schedule a different effect, replacing the previous one.

import { useState, useEffect } from "react"
const MyComponent = () => {
    const [count, setCount] = useState(0)

    useEffect(()=>{ // pass a function to useEffect
        document.title = `You clicked ${count} times` // in useEffect, you can access to the count in useState.
    })
}

Dependency

Dependency of useEffect decides when the useEffect hook runs based on the depenedency.

const MyComponent = () => { 
    const [count, setCount] = useState(0)
    useEffect(()=>{
        console.log(`${count} is increased by 1`)
    }, [count]) // [count] is a dependency of useEffect. If dependency given, useEffect would run only in the case of the dependency. If given emtpy array as a dependency, it will re-render at first time(initial render).
    handleClick(
        setCount(count + 1) //
    )
    return ( 
        <div>
            <button onclick={handleClick}>Click Me</button>
            <p>Increased count : {count}</p>
        </div>
    )
}

Custom hooks

To increase code reusability, you can create your own hook and import the hook in different components. Consider custom hook nothing more than importing a new module in Javascript. You write a function, export it, and import it in another file. Remember that hook's name should start with 'use'.

// useMyHook.js
export const useMyHook = () => { 
    return <div>I am a custom hook!</div>
}

import { useMyHook } from './useMyHook'
function MyComponent() { 
    return (
        <div>
            <h1>My First Hook</h2>
            {useMyHook()}
        </div>
    )
}
728x90

댓글


loading