Firstly , we should know what is global state?
Global state refers to data that needs to be shared across multiple components in a React application.
To manage global state Redux is a popular solution but there are other effective ways to manage global state without using it . React has built-in solutions.
Methods to Manage Global State:
- Context API: This is like the secret weapon already built into React. If you’ve got state or data that you need to pass down through multiple layers of components, Context API can really save the day. It allows us to share the state across the entire component tree without needing to pass props manually at every level.
Step 1 : We will create a Context using React.createContext().
const NewContext = React.createContext();
Step 2 : We will wrap our components with a Provider as it allows any component within it to access the global state.
<NewContext.Provider value={ /*global state */}>
<App/>
</NewContext.Provider>
Step 3 : We can use useContext hook in any deeply nested component to access that global state.
const value = useContext(NewContext);
- Custom Hooks : If we want to write reusable and clean code , custom hooks can be a fantastic option.
function useGlobalState(){
const [state , setState] = useState(initialState);
return {state , setState };
}
Instead of passing data(props) through many layers of components, or dealing with complicated state management systems , we can create a custom hook like useGlobalState() to handle the state.