React Fundamentals

0% completed

Previous
Next
Local and Global States

Positioning of states in your React application is important because it determines how efficiently your components can manage, share, and reuse data.

Local State

Local state refers to the state that is specific to a single component and internally maintained by the component. They are only relevant and needed within the component where it is defined.

Using local state, components can independently change and handle their data which leads to partitioning within the application.

Local states are not shared with other components unless passed down as a prop

Example:

Citing our previous Counter example, the count state variable is a local state as it is perculiar to the Counter component.

import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Current count: {count}</p> <button onClick={() => setCount(count + 1)}>Increase</button> </div> ); }

Global State

Global state refers to the state that needs to be accessible across multiple components in an application. It is useful when the same data must be shared by different parts of the application thereby, aiding communication among multiple components.

Global states are usually declared at the top level of an application's root component.

Example

Continuing our Counter example, we can declare a global state that can be accessed by more than one component.

import { useState } from 'react'; export default function App(){ const [message, setMessage] = useState('Welcome to the Counter App!'); return ( <div> <h1>{message}</h1> <Counter /> <Counter /> <button onClick={() => setMessage('Thanks for using the app!')}> Update Message </button> </div> ); }; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Current count: {count}</p> <button onClick={() => setCount(count + 1)}>Increase</button> </div> ); }

In this example, we have:

  • message as the global state resident and managed in the App component. It is updated with the button click in the App component.

  • count as the local state resident and managed in the Counter component. Each Counter component maintains its own count state using useState. The state of one Counter does not affect the state of another.

While coding in React, there are times when some local state variables need to be converted to global states to allow multiple components to share their data. This is where Lifting State Up comes into play. It is a term used to describe the process of moving state "one or more levels up" in the component tree to make it accessible to multiple components.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next