Languages
[Edit]
EN

React - create shared state across multiple components using custom solution

3 points
Created by:
Creg
9600

Writing applications in React it happens we need to share state between multiple components.

Thare are multiple ways to do it:

This article shows some custom hooks that lets to share state in simple way across multiple components. The motivation to state sharing can be as e.g. authentication, where user may login, logout and current state may be needed in any time and place.

The main advantages of the below solution are:

  • very small size
  • very good performance
  • posibility to read current state in any application lifecycle, what is not provided via React states. 

Practical exmaple

Edit

Runnable example is available here.

App.tsx file:

 

state.tsx file:

 

Alternative titles

  1. React - create and share state across multiple components using custom solution
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join