This code is where I modified the data, wherein I update the "checked" to whether "true" or "false". and this code works because when I console.log() it it updates the state.
    setRolesData((prevState) => {
        const newState = Array.from(prevState);
        newState[targetCb]["checked"] = e.target.checked;
        return newState;
    });
    console.log(rolesData);

Image of the result:

This code is where I loop thru the data that is updated, but the problem is it doesnt return the same data as the log data if tried for the second time.
    // get all checked roles
    const roleArr: any = [];
    rolesData.map((item, index) => {

        console.log(item.checked + " ^ " + item.name);

    });

Image of the Result:


useState() not updated when state is used in a loop
In React, components have a lifecycle that is based around the idea of preserving state. When you update a value in a component we effectively trigger a re-render of the component. So if you have a variable at the top of your component with a certain value and try to update this value inside a function, you'll find that this value gets reset. React is replacing the component including the JavaScript variables inside it.
In order to preserve any variables we use useState to persist the state of the component between re-renders. However, in a function, using useState does not save the value to state immediately. useState is an instruction that is sent to React that tells it that when the component re-renders, we need to save that value. If you try to access the value in state before your re-render has begun you will be using the "previous" value instead. In your case, your component will not re-render until the calling function has been completed.
So how do you listen for changes?
UseEffect is a special hook that takes an array of dependencies as "listeners". When we use useEffect and give it a value in state as a dependency, it's telling it to run the code inside the useEffect if there is a mutation to that value.
useEffect(() => {

    rolesData.map((item, index) => {
      console.log(item.checked + " ^ " + item.name);
    });

}, [rolesData]);

This code will run every time myState is changed, including on component initialisation. So we can use useEffect to process logic that requires the newly updated stateful values.
