Showing results for usestate boolean array
Search instead for use state boolean array

maybe you can use something like this?

const HanldeCheck = (index) => {
    setcheckBoxState(prevState => prevState.map((item, idx) => idx === index ? !item : item))
};
Answer from Hovakimyan on Stack Overflow
Top answer
1 of 6
25

setIsLoading is an async function and you cannot get the state value immediately after update.

setState actions are asynchronous and are batched for performance gains. setState() does not immediately mutate this. Thus the setState calls are asynchronous as well as batched for better UI experience and performance. This applies on both functional/Class components.

From React documentation

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. You could read more about this here

If you want to get the updated state value then use useEffect hook with dependency array. React will execute this hook after each state update.

const {useEffect, useState } = React;

const App = (props) => {
  const [isLoading, setIsLoading] = useState(false)
  const buttonHandler = () => {
    setIsLoading(current => !current)
  }

  useEffect( () => {
    console.log(isLoading);
}, [isLoading]);

  return (
    <div>
      <button onClick={buttonHandler} type="button">
        Change
      </button>

      {isLoading? "Loading...": null}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

    <div id="root">
      loading.....
    </div>

2 of 6
4

This is the expected behavior. You may want to use useEffect to access the latest value.

Here is a thread discussing the same issue: useState set method not reflecting change immediately

Hope this helps!

Discussions

reactjs - update boolean value in useState array - Stack Overflow
I have an useState with array in it, one of the value in the array is boolean. Im tring to update the value of the boolean by click. so this is the button function: let Completed = () => ... More on stackoverflow.com
🌐 stackoverflow.com
reactjs - React JS Typescript usestate with boolean - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
reactjs - useState Array boolean toggle - React Native - Stack Overflow
Beginner developer react native. im dealing with design pattern issue , i have multiple TouchableOpacity's in the same component (i have to keep it that way). for each one i have onPress function t... More on stackoverflow.com
🌐 stackoverflow.com
useState(Boolean) vs useState(false)
I'd even argue against it. More on reddit.com
🌐 r/reactjs
7
2
February 18, 2021
🌐
GitHub
gist.github.com › brookback › 26622ff6a7d11ed34f6e321cf79e81a4
A React hook for getting a single boolean value for when pairs in an array change. · GitHub
A React hook for getting a single boolean value for when pairs in an array change. ... import React, { useState } from 'react'; interface Props { text: string; } const MyComponent = (props: Props) => { const [currentText, setText] = ...
🌐
DEV Community
dev.to › alexkhismatulin › update-boolean-state-right-with-react-hooks-3k2i
Update boolean state right with React Hooks - DEV Community
May 11, 2020 - Then we replace isToggled with the reference in the dependencies array and callback itself and that's it! Let's create a custom hook that would return a current boolean state and a toggle method that is changing a boolean value and never gets re-created · // it might be a project-level reusable hook const useToggle = (initialState) => { const [isToggled, setIsToggled] = React.useState(initialState); const isToggledRef = React.useRef(isToggled); // put [isToggledRef, setIsToggled] into the useCallback's dependencies array // these values never change so the calllback is not going to be ever re
🌐
Medium
medium.com › @urza.p › how-to-type-usestate-in-react-with-typescript-13c4dae75b1b
How to Type useState in React with TypeScript | by Urja | Medium
June 4, 2025 - useState<number>(0) // number useState<string>("") // string useState<boolean>(false) // boolean useState<string | undefined>(undefined) // undefined useState<{ id: number; name: string }>({ id: 0, name: "" }) // object useState<string[]>([]) // array useState<"loading" | "error" | "success">("loading") // literal ·
Find elsewhere
🌐
Linguine Code
linguinecode.com › home › blog › how to use set types on react usestate with typescript
How to use set types on React useState with TypeScript
September 11, 2020 - In today’s short article, I will go over how to define your useState hook with TypeScript. interface PersonProps { name: string; age: number; hobbies: Array<string>; isCool: boolean; } // Boolean type const [isCool] = React.useState<boolean>(true); // String type const [name] = React.useState<string>('Ruben'); // Number type const [age] = React.useState<number>(28); // Null or undefined const [random] = React.useState<null | undefined>(); // Array of string const [hobbies] = React.useState<Array<string>>(['soccer', 'cooking', 'code']); // Custom interface const [person] = React.useState<PersonProps>({ isCool, name, age, hobbies }); Let’s go over it really quickly.
🌐
Dave Ceddia
daveceddia.com › usestate-hook-examples
4 Examples of the useState Hook
July 12, 2020 - But with hooks, the state can be any type you want – you can useState with an array, useState an object, a number, a boolean, a string, whatever you need.
🌐
React
react.dev › reference › react › useState
useState – React
useState returns an array with exactly two values:
🌐
GitHub
github.com › scottbamford › use-toggle-state
GitHub - scottbamford/use-toggle-state: A useState like hook for boolean values that returns the state, and a ToggleStateAction instead of a SetStateAction that allows the setState callback to be called without passing any arguments to simply toggle the boolean value.
A useState like hook for boolean values that returns the state, and a ToggleStateAction instead of a SetStateAction that allows the setState callback to be called without passing any arguments to simply toggle the boolean value.
Author   scottbamford
🌐
LogRocket
blog.logrocket.com › home › usestate in react: a complete guide
useState in React: A complete guide - LogRocket Blog
October 22, 2024 - React useState allows you to add state to functional components, returning an array with two values: current state and a function to update it.
🌐
CodeSandbox
codesandbox.io › s › usestate-boolean-basic-example-iepcl
useState boolean basic example - CodeSandbox
January 30, 2020 - useState boolean basic example by sandagolcea using react, react-dom, react-scripts
Published   Jun 10, 2019
Author   sandagolcea
🌐
Jstopics
jstopics.com › reactjs › usestate-with-typescript
UseState with TypeScript | JSTopics
First, we import useState hook from React and initialise it at the beginning of our component. As you can see, we use array destructuring syntax to create the state. ... The first element is the piece of state in our case boolean called showModal and the second element is the so-called dispatch function that updates this piece of state.
Top answer
1 of 2
4

One of the approaches is to store item names in an array or object and then check if the particular item were selected.

Here is another approach you could use:

const HomeScreen = () => {
    const itemsData = [
        { name: 'Eggs', image: 'image require here', isSelected: false },
        { name: 'Pasta', image: '', isSelected: false },
        { name: 'Fish', image: '', isSelected: false },
    ];

    const [items, setItems] = useState(itemsData);

    const handleSelectItem = (selectedItemIndex) => {
        const itemsToSelect = items.map((item, index) => {
        if (selectedItemIndex === index) item.isSelected = !item.isSelected;
        return item;
        }, []);

        setItems(itemsToSelect);

        // your logic here
        // AddToPanetry(item[selectedItemIndex].name)
    };

    const renderItem = (item, index) => {
        const isSelected = items[index].isSelected;

        return (
        <TouchableOpacity
            style={[styles.button, isSelected && styles.selectedButton]}
            onPress={() => handleSelectItem(index)}>
            {/* <Image source={item.image} /> */}
            <Text>{item.name}</Text>
        </TouchableOpacity>
        );
    };

    return (
        <View>
        <ScrollView>
            {itemsData.map((item, index) => renderItem(item, index))}
        </ScrollView>
        </View>
    );
};

const styles = StyleSheet.create({
  button: {
    backgroundColor: 'white',
    padding: 20,
  },
  selectedButton: {
    backgroundColor: 'pink',
  },
});
2 of 2
1

There are 2 options depending on your needs.

  1. You could keep your all of your data and selected state in a single stateful array. On press, you need to find the item in the array that will update.
export default function Grocery({ navigation }) {
  const [state, setState] = React.useState([ { label: 'pasta', pressed: false, }, { label: 'eggs', pressed: false, }, { label: 'fish', pressed: false, }, { label: 'salad', pressed: false, }, ]);

  const handlePress = (i) => {
    const newState = [...state];
    newState[i].pressed = !state[i].pressed;
    setState(newState);
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <FlatList
        data={state}
        ListHeaderComponent={() => (
          <Button
            title="home"
            onPress={() => {console.log('press home')}}>
            press
          </Button>
        )}
        renderItem={({ item, index }) => (
          <TouchableOpacity
            key={index}
            id={index}
            onPress={() => handlePress(index)}
            style={[
              styles.flatListTouchable,
              item.pressed && styles.flatListTouchablePressed,
            ]}>
            <Text style={styles.flatListTouchableText}>{item.label}</Text>
          </TouchableOpacity>
        )}
      />
    </SafeAreaView>
  );
}

Snack


  1. You could keep your data and selected state separately. The selected state is managed in the child component.
const data = [ { label: 'pasta', }, { label: 'eggs', }, { label: 'fish', }, { label: 'salad', }, ];

export default function Grocery({ navigation }) {
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <FlatList
        data={data}
        ListHeaderComponent={() => (
          <Button
            title="home"
            onPress={() => {
              console.log('press home');
            }}>
            press
          </Button>
        )}
        renderItem={({ item, index }) => (
          <RenderItem item={item} index={index} />
        )}
      />
    </SafeAreaView>
  );
}

const RenderItem = ({ item, index }) => {
  const [pressed, setPressed] = React.useState(false);

  const handlePress = () => {
    setPressed(!pressed);
  };

  return (
    <TouchableOpacity
      key={index}
      id={index}
      onPress={handlePress}
      style={[
        styles.flatListTouchable,
        pressed && styles.flatListTouchablePressed,
      ]}>
      <Text style={styles.flatListTouchableText}>{item.label}</Text>
    </TouchableOpacity>
  );
};

Snack

🌐
Reddit
reddit.com › r/reactjs › usestate(boolean) vs usestate(false)
r/reactjs on Reddit: useState(Boolean) vs useState(false)
February 18, 2021 -

Is it a thing to set default state values using primitive type constructors when applicable? e.g.

// Boolean (defaults to false)
const [active, setActive] = useState(Boolean);
const [active, setActive] = useState(false);

// String (defaults to "") 
const [searchTerm, setSearchTerm] = useState(String); 
const [searchTerm, setSearchTerm] = useState("");

// Number (defaults to 0)
...

Another developer who was learning React at the same time as me said I should do it this way and I pretty much have been doing it this way for the last 2 years.

I figured it helped me write more declarative code and never gave it much more thought until this week. I've been trying to find any information discussing this but haven't found a thing.

Is there any explanation for or against this that people can think of? Do many other people declare state like this?

🌐
Selftaughttxg
selftaughttxg.com › 2023 › 04-23 › creating-a-true-false-toggle-in-react-with-usestate-hook-for-beginners
Creating a True/False Toggle in React with useState Hook for Beginners |
April 14, 2023 - The useState hook returns an array with two values: the current state value and a state updater function to update that value.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
React useState Help - Update item in Array of Objects
February 8, 2024 - You can reroll the dice and you can click on a die to freeze it (keep it’s number/don’t reroll) I’m storing dice data in a useState that holds an array of objects When I try to update the useState object by directly reversing the die’s isFrozen boolean, it doesn’t work.
Top answer
1 of 2
4

Your approach is right just one minor thing that you trying to achieve here is wrong.

setEmailNotifications({
  ...emailNotifications,
  [event.target.id]: !event.target.id, //Here
});

when you are setting dynamic value to the state you are expecting it to be the Boolean value which is not

solution:

setEmailNotifications({
  ...emailNotifications,
  [event.target.id]: !emailNotifications[event.target.id],
});
2 of 2
3

@kunal panchal's answer is totally valid Javascript, but it does cause a Typescript error because the type of event.target.id is string so Typescript does not know for sure that it's a valid key of emailNotifications. You have to assert that it is correct by using as.

!emailNotifications[event.target.id as keyof EmailNotifications]

One way to avoid this is to get the boolean value by looking at the checked property on the input rather than toggling the state.

As a sidenote, it's a good best practice to get the current state by using a setState callback so that you always get the correct value if multiple updates are batched together.

const _handleEmailNotificationsSettings = (
  event: React.ChangeEvent<HTMLInputElement>
) => {
  setEmailNotifications(prevState => ({
    ...prevState,
    [event.target.id]: event.target.checked,
  }));
};

This is probably the best solution for a checkbox.


Another approach which is more flexible to other situations is to use a curried function. Instead of getting the property from the event.target.id, where it will always be string, we pass the property as an argument to create an individual handler for each property.

const handleEmailNotificationsSettings = (
  property: keyof EmailNotifications
) => () => {
  setEmailNotifications((prevState) => ({
    ...prevState,
    [property]: !emailNotifications[property]
  }));
};

or

const handleEmailNotificationsSettings = (
  property: keyof EmailNotifications
) => (event: React.ChangeEvent<HTMLInputElement>) => {
  setEmailNotifications((prevState) => ({
    ...prevState,
    [property]: event.target.checked
  }));
};

which you use like this:

<input
  type="checkbox"
  checked={emailNotifications.favourites}
  onChange={handleEmailNotificationsSettings("favourites")}
/>

Those solutions avoid having to make as assertions in the event handler, but sometimes they are inevitable. I am looping through your state using (Object.keys(emailNotifications) and I need to make an assertion there because Object.keys always returns string[].

import React, { useState } from "react";

// I am defining this separately so that I can use typeof to extract the type
// you don't need to do this if you have the type defined elsewhere
const initialNotifications = {
  rating: false,
  favourites: false,
  payments: false,
  refunds: false,
  sales: false
};

type EmailNotifications = typeof initialNotifications;

const MyComponent = () => {
  // you don't really need to declare the type when you have an initial value
  const [emailNotifications, setEmailNotifications] = useState(
    initialNotifications
  );

  const handleEmailNotificationsSettings = (
    property: keyof EmailNotifications
  ) => (event: React.ChangeEvent<HTMLInputElement>) => {
    setEmailNotifications((prevState) => ({
      ...prevState,
      [property]: event.target.checked
    }));
  };

  return (
    <div>
      {(Object.keys(emailNotifications) as Array<keyof EmailNotifications>).map(
        (property) => (
          <div key={property}>
            <label>
              <input
                type="checkbox"
                id={property}
                checked={emailNotifications[property]}
                onChange={handleEmailNotificationsSettings(property)}
              />
              {property}
            </label>
          </div>
        )
      )}
    </div>
  );
};

export default MyComponent;