Implementing React's UseState in C#

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>() : (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


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!


No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website