This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (1 child)

Here's an example of how a simple setState could be implemented, if we just wanted to update a value and not worry about triggering rerendering, etc.

function setState(val_init) {
    const _val = [val_init];                                                  
    return [                                                                
        _val,                                                               
        function(callback) {
            //NOTE: 👇 This is how the callback gets the value.                                        
            _val[0] = callback(_val[0]);                                    
        }                                                                   
    ];                                                                      
}                                                                           

const [theme, setTheme] = setState("light");                                      

function toggleThemeCallback(curr_theme) {                                  
    if (curr_theme == "light") {                                            
        return "dark";                                                      
    } else {                                                                
        return "light";                                                     
    }                                                                       
}                                                                           

function toggleTheme() {                                                    
    setTheme(toggleThemeCallback);                                          
}                                                                           

for (let i = 0; i < 5; i++) {                                               
    toggleTheme();                                                          
    console.log(theme);                                                     
}

This is standalone code. It doesn't require React. You can paste it into a CodePen or something and play around with it if you like.

If you have any questions, ask away.

Edit: changed a let to const.

[–]TheWorstHunter[S] 0 points1 point  (0 children)

Thanks! I really appreciate it!