State in React.js represents a component’s local state or information. It can be changed and updated. Below are some methods to handle the state in React.js:
1. Constructor function: The state of a component can be declared in its constructor. When you define the constructor method in the class, you must call ‘super(props)’ to initialize the ‘this’ props in the constructor.
Example:
```
constructor(props){
super(props)
this.state = {
name: ‘John’,
age: 23
}
}
```
1. setState method: After declaring state inside a constructor, there might be scenarios when state needs to be updated. It can be done using ‘setState’ method. ‘setState’ performs a shallow merge of state and does not mutate the original state object.
Example:
```
this.setState({age: 24})
```
1. useState Hook: In functional components, states can be managed using the ‘useState’ Hook. The ‘useState’ hook lets you add state to functional components.
Example:
```
const [name, setName] = useState(‘John’);
const [age, setAge] = useState(23);
```
Here, ‘name’ and ‘age’ are state variables, and setName and setAge are the corresponding setter functions that can be used to update these variables.
1. Using the ‘Context’ API: This provides a way to pass data through the component tree without having to pass props down manually at every level.
1. Using a State Management Library: There are some libraries like Redux, MobX, which are widely used for managing state in large applications.
1. Reduction of Component State: Sometimes it’s better to reduce using states as much as possible to avoid complexity. For example, if a value can be derived by props, or other state or it’s just used for rendering then there might not be a need to make it as state.
1. Using ‘useReducer’ Hook: ‘useReducer’ is a hook that is used for state management in React. It is an alternative to ‘useState’ and is preferable when you have complex state logic that involves multiple sub-values. It also allows you to optimize performance for components that trigger deep updates.