How State in React works?
Tags: webdev, react, beginners, javascript
Published: 2023-01-06 06:54:07

Hello! It's me again, your React Toist😁. This is a 2/4 part article highlighting some React concepts, check [React state in 2 min](https://dev.to/kinginthenorthcodez/react-state-in-2-min-27bo).Lets dive in🏊🏽.

![Squiddy toist](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywk7umw3xlx2ifo60gv6.gif)


## Mutation on state
 - Mutation is the ability to affect change and react provides a
   clear rule or guidline on how to affect the react state.
 - React says no direct change is allowed on state, any changes or 
   update should be done through the state function updater that 
   react provides at the time of creating the state.
 - Lets consider this:

```
import React {useState} from 'react'
  const StateInReact= () =>{
   //creates and gives initial value
   const[title, setTitle]= useState('State in React!') 
    //Not allowed!
    title= "New state value"
   // Allowed
    setTitle('new state value')
  return(<h1>{title}</h1>) //access state
}
```

## Scope and Access
- In React state is either local to the compenent(component state) 
  or global to all components(app state) also known as shared state. And this defines scope to which component can access that state.
- Every component can defined its own state and share it with other components that need access to or use that state.
- React allows this by passing down state data from a parent 
  component(component that defined state) to child 
  component(component recieving state) through whats called props 
  short for (properties) or prop drilling.
- Its this techique that allows state to be shared among 
  components that needs it.
- Lets consider this:

```
 import React {useState} from 'react'
  const StateInReact= () =>{
   //creates and gives initial value
   const[title, setTitle]= useState('State in React!') 
    //Not allowed!
    title= "New state value"
   // Allowed
    setTitle('new state value')
  return(
         <>
          <AnotherComp title = {title}/> //pass state as prop
         </>
       ) 
}

const AnotherComp =(props)=> {
return(<h1>{props.title}</h1>) // access state from props
}


```

- But this way of state sharing would bring unneccessary work
  for other child components that have no use of the state but 
  just to pass it along down to the next, until the one that has 
  use for it. 
- Solution? React allows you also to define a global state , so 
  that any component can access it directly and use the state 
  whenever needed.
- This is possible by defining a context(scope) through the 
  context API, that hooks state to a provider wraping your 
  application or main component in your app.
- Thats how global state is provided and achieved in your react app.
- Lets consider this: 

```
 import React, { useState, useContext } from 'react';
import data from '../birthday/Data';

const PersonContext = React.createContext(); // has two components named provider and consumer
const ContextAPI = () => {
  const [people, setPeople] = useState(data);
  const removeItem = (id) => {
    setPeople((people) => {
      return people.filter((person) => person.id !== id);
    });
  };
  return (
    <PersonContext.Provider value={{ removeItem, people }}>
      <h2>ContextAPI</h2>
      <List />
    </PersonContext.Provider>
  );
};

const List = () => {
  const { people } = useContext(PersonContext);
  return (
    <>
      {people.map((person) => {
        return <SinglePerson key={person.id} person={person} />;
      })}
    </>
  );
};

const SinglePerson = ({ person }) => {
  const { removeItem } = useContext(PersonContext);
  return (
    <div key={person.id}>
      <h4>{person.name}</h4>
      <button type='button' onClick={() => removeItem(person.id)}>
        remove
      </button>
    </div>
  );
};

export default ContextAPI;

```
- This way of state management is okay when your app is small and does not involve complex state logic.
- But as your app scales or grow you would need to use dedicated 
  tools for managing your state such as  [Redux](https://redux.js.org/introduction/getting-started), [MobX](https://mobx.js.org/README.html) etc
- On how to use such state management tools like Redux , i will 
 do a separate article on that. So do look out for it once it's 
 published. 
- You can also check out the source code on my [github](https://github.com/kinginthenorthcodez/oraion) were i have documented this [resource](https://github.com/kinginthenorthcodez/oraion/blob/5ed68bf3a83862a88ce9b6c16fa878a352883034/src/1-contextAPI/contextAPI.js).

## Sycronization
- Sycronization is the ability to respond or react to updates and 
  changes in data/state across data and rendering components.
- What this means is that, when your data or state updates or changes, every other component that uses or access that data ,should be able to recieve and update its data with the current state/data.
- This gives the app or component ability to update UI/re- 
  rendering with current state.
- A simple example is form that uses controlled inputs.
- You can also archive this with React-router data apis. Will 
  write and show you how in my next article about react-router's 
  super powers🥷🏽.

### Summary
  - Every time you update state data that UI uses, you send that 
    data to UI so it can update its UI acordingly. 

## One directional flow of data
 - Providing a single source of truth is how react state manages 
   its state or data.
 - We have seen this on mutatation of state and this why.
 - This is also the basic principle for all state management 
   libraries like redux and state immutabality is archied.
 - For a more indepth about this will be convered in redux and 
   state management in react.

## Conclusion:
 - Whether you building a small app or complex app , you will want 
   to store some data, to provide a custom experience to the user(aka 
   user experience).
 - And state is how you archieve just that in react, therefore 
   knowing how state works is the right direction to put your feet 
  in waters of React.

**Hope you had a wonderful read ,and some quetion answered.**

**Happy coding!!🚀**