reactjsreact-nativeuse-stateuse-context

React Native, node js - update object in different scripts


I'm building an app in React Native, and I am trying to understand if I need to use useState & useContext to export a user info object, or I can just get the object from the script, change it, and it will be changed to all the other scripts. (or if there is a better way to do it so)

Thanks in advance :)


Solution

  • If you update data in your component, always use useState.

    Furthermore if you store an array or an object into your state, it's a good practice to update the array/object, and then update your state with a spread operator (this will create a new array/object, and fired your useEffect and UI)

    Example :

    If you do a simple :

    const [stateArray, setStateArray] = useState(["foo"])
    stateArray[0] = "new foo"
    

    All the components that consume the stateArray[0] will not update and continue to display a simple foo

    This is caused becaused this update doesn't triggered a refresh as you're array isn't update, but one of it's component (not detect by React).

    If you want an update, you need to do :

    const [stateArray, setStateArray] = useState(["foo"])
    stateArray[0] = "new foo"
    setStateArray([...stateArray])
    

    This will create a new array, and as such, triggered a new render of your component.

    And the same logic applied for object, if you only update one of its value, there will be no update, you need to create a new object :

    Example :

    const [stateObject, setStateObject] = useState({foo: "foo"})
    stateObject.foo = "new foo"
    setStateObject({...stateObject})