본문 바로가기

Frontend/React

Hooks - State Management (useState, useReducer)

반응형

The information shown on one page is not available on the other pages without a server or other storage. React provides various hooks to manage status across components that can represent different pages without needing a server or other client storage libraries. Let's see how we can use them!

List of Contents

Project Set Up

Create an application to see how it is working.

Creating a React App

 

React

React is the most papular framework followed by Angular and Vue. React, like Angular uses components to build an application. However, React does not come with native features like Angular. Instead, it uses other libraries which makes React compact and sma

jin-co.tistory.com

useState

Initializing the State

Import the 'useState' library from the react

import { useState } from 'react'

Initialize the useState as shown below. The first value in the array is the name of the target and the second value is a function to update the target. Insert the initial value of the target in the parenthesis that comes after useState

const [post, SetPost] = useState()

Let's see if it works

Updating the Target

Add a function to reset the value of the target inside a function

function updatePost() {
  setPost(2)
}

Create a button with an event that calls the outer function above to test

<button onClick={updatePost}>Update</button>

Ren the app and click the button, then you will see the value is updated (This does not change the original value)

State alose provides the previous value of the target. We can access the previous value like below

setPost((pre) => {
  setPost(pre++)
})

useReducer

In Reducer, we create a function file that has the status and data object as parameters. The data object includes a type which is a string to determine what should be done.

Creating a Reducer Function

Create a JS file to add a function to change the statues.

The basic code for the function is as follows.

export const Reducer = (state, action) => {
  switch (action.type) {
    case 'TYPE_1':      
      return {
        ...state        
      }

    default:
      return state
  }
}

Initializing the Reducer

To initialize the reducer, we need the state and the initial value which will be passed to the function we created above when we update the status.

const initialState = {}
const [state, dispatch] = useReducer(<reducerName>, <initialStateName>)

Updating the Status

Add a function to update the status. Use the second variable, dispatch, we initialized above and add a type and new data.

const updateUser = () => {
  dispatch({
    type: 'UPDATE_USER',
    payload: ['user4', 'user5', 'user6']
  })
}

Go back to the reducer function file and update the type (as you can see the type is only a condition). In the return statement add the data. The state has the previous state and we use the spread operation to use the same value for the data that is not being updated.

In this writing, we have seen how to use the hooks that allow us to manage status in React.

 

728x90
반응형

'Frontend > React' 카테고리의 다른 글

React Library - React Router DOM  (0) 2023.05.02
React Library - Framer Motion  (0) 2023.05.01
Displaying a List  (1) 2023.04.17
React - Creating a Template  (0) 2023.04.12
React  (1) 2023.03.09