Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Different ways of setting State in React
Jess Alejo
Jess Alejo

Posted on

     

Different ways of setting State in React

In React, theuseState hook is used to manage state in functional components. There are several ways to set or update the value of a state variable usinguseState. Below are different methods and examples to demonstrate how you can set or update state values.

1.Setting Initial State

The most basic way to initialize state is by passing an initial value touseState.

importReact,{useState}from'react';functionApp(){const[count,setCount]=useState(0);return(<div><p>Count:{count}</p><buttononClick={()=>setCount(10)}>Set Count to 10</button></div>);}
Enter fullscreen modeExit fullscreen mode
  • Here,useState(0) initializes thecount state to0.
  • ThesetCount(10) function sets thecount state to10 when the button is clicked.

2.Updating State Based on the Previous State

When updating state based on the previous state, it's important to use thefunctional form of the state setter function. This ensures that you're working with the most up-to-date state, especially in asynchronous scenarios.

importReact,{useState}from'react';functionApp(){const[count,setCount]=useState(0);constincrement=()=>{setCount((prevCount)=>prevCount+1);// Functional update};constdecrement=()=>{setCount((prevCount)=>prevCount-1);// Functional update};return(<div><p>Count:{count}</p><buttononClick={increment}>Increment</button><buttononClick={decrement}>Decrement</button></div>);}
Enter fullscreen modeExit fullscreen mode
  • In this example,setCount((prevCount) => prevCount + 1) updates thecount state based on its previous value.
  • This is particularly useful when multiple state updates might happen in quick succession (e.g., inside loops or asynchronous functions).

3.Updating Complex State (Objects or Arrays)

When dealing with objects or arrays, you need to be careful because React's state updates areshallow. This means that you should always create a new object or array when updating state to ensure React detects the change.

Example with Objects:

importReact,{useState}from'react';functionApp(){const[user,setUser]=useState({name:'John',age:30});constupdateName=()=>{setUser((prevUser)=>({...prevUser,name:'Jane'}));// Spread operator to copy previous state};constupdateAge=()=>{setUser((prevUser)=>({...prevUser,age:35}));// Spread operator to copy previous state};return(<div><p>Name:{user.name}, Age:{user.age}</p><buttononClick={updateName}>Change Name to Jane</button><buttononClick={updateAge}>Change Age to 35</button></div>);}
Enter fullscreen modeExit fullscreen mode
  • Here,setUser is used to update theuser object.
  • We use thespread operator (...) to create a shallow copy of the previous state and then override specific properties (name orage).

Example with Arrays:

importReact,{useState}from'react';functionApp(){const[items,setItems]=useState([1,2,3]);constaddItem=()=>{setItems((prevItems)=>[...prevItems,prevItems.length+1]);// Add a new item};constremoveItem=()=>{setItems((prevItems)=>prevItems.slice(0,-1));// Remove the last item};return(<div><p>Items:{items.join(',')}</p><buttononClick={addItem}>Add Item</button><buttononClick={removeItem}>Remove Item</button></div>);}
Enter fullscreen modeExit fullscreen mode
  • In this example,setItems is used to update theitems array.
  • To add an item, we spread the previous array and append a new element.
  • To remove an item, we useslice to create a new array without the last element.

4.Batching Multiple State Updates

React automatically batches state updates for performance optimization. However, if you want to ensure multiple state updates are batched together, you can use functional updates.

importReact,{useState}from'react';functionApp(){const[count,setCount]=useState(0);const[message,setMessage]=useState('Initial Message');constupdateBoth=()=>{setCount((prevCount)=>prevCount+1);setMessage((prevMessage)=>`${prevMessage} Updated`);};return(<div><p>Count:{count}</p><p>Message:{message}</p><buttononClick={updateBoth}>Update Both</button></div>);}
Enter fullscreen modeExit fullscreen mode
  • In this example, bothsetCount andsetMessage are called in sequence.
  • React will batch these updates together, ensuring that the component re-renders only once.

5.Lazy Initialization of State

You can pass a function touseState if the initial state requires some computation or is expensive to calculate. This function will only run once during the initial render.

importReact,{useState}from'react';functionApp(){constcomputeInitialValue=()=>{console.log('Computing initial value...');return42;};const[value,setValue]=useState(()=>computeInitialValue());return(<div><p>Value:{value}</p><buttononClick={()=>setValue(100)}>Set Value to 100</button></div>);}
Enter fullscreen modeExit fullscreen mode
  • Here,computeInitialValue is only called once during the initial render, thanks to the lazy initialization pattern.
  • This is useful when the initial state calculation is expensive or involves side effects.

6.Resetting State to Initial Value

Sometimes you may want to reset the state to its initial value. You can do this by storing the initial value in a variable and using it to reset the state.

importReact,{useState}from'react';functionApp(){constinitialValue=0;const[count,setCount]=useState(initialValue);constresetCount=()=>{setCount(initialValue);};return(<div><p>Count:{count}</p><buttononClick={()=>setCount(count+1)}>Increment</button><buttononClick={resetCount}>Reset</button></div>);}
Enter fullscreen modeExit fullscreen mode
  • In this example,initialValue is stored in a variable, andresetCount resets thecount state to0.

Summary of Different Ways to Set State:

  1. Directly setting a new value:setState(newValue)
  2. Updating based on the previous state:setState((prevState) => newState)
  3. Updating complex state (objects/arrays): Use the spread operator (...) to create a new object or array.
  4. Batching multiple state updates: React automatically batches updates, but you can use functional updates to ensure consistency.
  5. Lazy initialization: Pass a function touseState for expensive initial state calculations.
  6. Resetting state: Store the initial value in a variable and reset the state using that value.

These techniques give you flexibility in managing state in React applications, whether you're dealing with simple values, complex objects, or arrays.

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
pengeszikra profile image
Peter Vivo
Pipeline operator and touch bar fanatic from Hungary.God speed you!
  • Location
    Pomaz
  • Education
    streetwise
  • Work
    full stack developer at TCS
  • Joined

Why don't like useReducer for complex solution?

CollapseExpand
 
jessalejo profile image
Jess Alejo
I write code
  • Joined

Thanks for the reminder! I’m still getting the hang of React since I’m pretty new to it, and I’ve already forgotten some of what I learned a while back. But don’t worry, I’ll catch up and be there soon! 😊

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I write code
  • Joined

More fromJess Alejo

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp