Part 2 - Mastering the Hidden Features of useState Hook in React: Tips and Tricks for Writing Efficient and Maintainable Code.

Part 2 - Mastering the Hidden Features of useState Hook in React: Tips and Tricks for Writing Efficient and Maintainable Code.

Hello Everyone,

This is Part 2 of my Mastering the Hidden Features of useState Hook in React series. You can check Part 1 from the link below.


4. useState with an object

It's important to note that useState hook can also be used with objects and arrays. When updating state with an object or array, it's important to use the spread operator to create a new copy of the object or array. If you directly update the object or array, React will not recognize the change and the component will not re-render.

const [user, setUser] = useState({name: 'John', age: 30})

const updateAge = (newAge) => {
? setUser({...user, age: newAge});
};        

In this example, when calling updateAge function, we are creating a new object by spreading the previous user object and updating the age property with the newAge.


5. useState with context

The useState hook can be used in combination with the useContext hook to access and update state across multiple components in your application. This can be useful for sharing global state, such as a user's authentication status or theme settings.

const UserContext = React.createContext();

const App = () => {
? const [user, setUser] = useState({});
? return (
? ? <UserContext.Provider value={{ user, setUser }}>
? ? ? <NavBar />
? ? ? <ProfilePage />
? ? </UserContext.Provider>
? );
};


const NavBar = () => {
? const { user } = useContext(UserContext);
? return <div>Welcome, {user.name}</div>;
};


const ProfilePage = () => {
? const { user, setUser } = useContext(UserContext);
? const updateName = (newName) => {
? ? setUser({...user, name: newName});
? }

? return (
? ? <div>
? ? ? <div>{user.name}</div>
? ? ? <button onClick={() => updateName('Jane')}>Update name</button>
? ? </div>
? );
};        

In this example, the user state and setUser function are wrapped in a context provider, which allows both the NavBar and ProfilePage components to access and update the user state.

I hope you are enjoying the articles in the series, I will keep it as dead simple as possible to make it easier to understand.

Thank you ??

Happy Coding...

要查看或添加评论,请登录

?? M.的更多文章

社区洞察

其他会员也浏览了