David
David

Reputation: 528

Is there a way to dynamicaly create state with useState in React

I am building a react app that has input fields that should be stored to the state. I can easily store these values using the useState hook. The challenge I am facing however is that I do not know the fields as I pull them from a database and they can change. Is there a way that I can set up the useState to be created dynamically so they can be added or removed based on what is in the database. eg.

The fields would be pulled from a database and stored into an array like so:

const fields = [userName, userAge, userLocation, userOccupation]; 

The useState would be

const[username, setUserName] = useState('');
const[userAge, setUserAge] = useState('');
...

If I added another item to the array, it should automatically create state for that item. What would be the best way to achieve this? Thanks.

Upvotes: 0

Views: 526

Answers (1)

Emre Bener
Emre Bener

Reputation: 1412

One way to dynamically create state variables based on the fields array is to use the useReducer hook in combination with a reducer function.

For example;

import { useReducer } from 'react';

const fields = [userName, userAge, userLocation, userOccupation]; 

const initialState = {};
fields.forEach(field => {
  initialState[field] = '';
});

const reducer = (state, action) => {
  switch (action.type) {
    case 'SET_FIELD_VALUE':
      return {
        ...state,
        [action.field]: action.value
      };
    default:
      return state;
  }
};

const [state, dispatch] = useReducer(reducer, initialState);

// You can then use dispatch to update the state for a specific field
dispatch({ type: 'SET_FIELD_VALUE', field: 'userName', value: 'John' });

This way, you can dynamically create state variables for each field in the fields array, and use the dispatch function to update the state for a specific field.

Upvotes: 2

Related Questions