0

Implementing React's UseState in C#

 1 year ago
source link: https://weblogs.asp.net/ricardoperes/implementing-react-s-usestate-in-c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Implementing React's UseState in C#

Monday, March 20, 2023

It's been a long time since my last post! Well, I'll try to change that. For now, I'll just leave something I was playing with: an implementation in C# of React's UseState function (or hook, in React terminology). This is merely for fun, but, hey, who knows if it might help someone!

public static class React
{
public static (Func<T>, Action<T>) UseState<T>(T defaultValue = default) { var item = defaultValue ?? ((typeof(T) != typeof(string)) ? Activator.CreateInstance() : (T) (object) string.Empty); Func<T> getter = () => item; Action<T> setter = (T value) => item = value; return (getter, setter); }
}

And here's how to use it:

var (get, set) = React.UseState("123");

var current = get(); //123

set("456");

var after = get();   //456

The idea here is simple: React.UseState returns a tuple which includes both a getter and a setter lambda; you use them to manipulate some private state, of which you can set the initial value. Only through these lambdas can this be achieved. One word of caution: it won't work with interfaces, abstract classes or types that do not have a public parameterless constructor, unless you pass the default value.

As always, hope you enjoy it! Feel free to share your thoughts!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK